From 8e7716af2ea656ef06f00e62bb1e234e8796cc23 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 17:28:28 +0000 Subject: [PATCH 1/4] fix(rust): the run drops a host's value of any depth without recursing --- rust/README.md | 2 + rust/crates/psychoscript/src/host.rs | 72 +++++++++++++-- rust/crates/psychoscript/src/host_function.rs | 61 +++++++++++++ rust/crates/psychoscript/src/snapshot.rs | 4 +- rust/crates/psychoscript/tests/value_depth.rs | 91 ++++++++++++++++++- 5 files changed, 214 insertions(+), 16 deletions(-) diff --git a/rust/README.md b/rust/README.md index b0cca7c6..0608ab7a 100644 --- a/rust/README.md +++ b/rust/README.md @@ -155,6 +155,8 @@ Known differences: `timeout_ms` and `slice_ms`, as in the reference. `regress` has no step budget; bound untrusted patterns or inputs. - A saved state changed since it was saved is refused (its header holds a hash of it), but resuming doesn't validate a forged one in full and may panic (in safe Rust): store saved states as you would code. +- The run drops what a host gives it without recursing, at any depth, but a `HostValue` a host makes and drops itself + drops recursively, like a `serde_json::Value`: one nested past about 10,000 levels is the host's to take apart. - On wasm32, a run driven as a future that waits on a host call notices its timeout only when it is next polled. - The round-trip conformance run (`PSYCHOSCRIPT_ROUNDTRIP=1`) failed once on a heavily loaded machine and didn't reproduce in 52 runs since; its quiet panic hook doesn't name the failing case. diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 35992caf..1ddd09ba 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -105,7 +105,7 @@ pub enum Settlement { /// A host call's outcome, with what converting it needs. pub struct Settled { - pub result: HostResult, + pub result: Held, /// Names the call in conversion errors. pub label: String, /// The global host function whose `snapshot` hooks save functions in the value, by label. @@ -114,6 +114,40 @@ pub struct Settled { pub site: Option, } +/// A host call's outcome, which the host makes and may nest at any depth: dropped without recursing. Taken out, it +/// leaves `undefined` behind, which holds nothing to drop. +pub struct Held(std::mem::ManuallyDrop); + +impl Held { + #[inline] + pub fn take(&mut self) -> HostResult { + std::mem::replace(&mut *self.0, Ok(HostValue::Undefined)) + } +} + +impl std::ops::Deref for Held { + type Target = HostResult; + + fn deref(&self) -> &HostResult { + &self.0 + } +} + +impl Drop for Held { + #[inline] + fn drop(&mut self) { + let (Ok(v) | Err(v)) = &mut *self.0; + if !matches!(v, HostValue::Undefined) { + dispose(v); + } + } +} + +#[cold] +fn dispose(v: &mut HostValue) { + std::mem::take(v).discard(); +} + impl Settlement { pub(crate) fn host( result: HostResult, @@ -122,7 +156,7 @@ impl Settlement { site: Option, ) -> Self { Settlement::Host(Box::new(Settled { - result, + result: Held(std::mem::ManuallyDrop::new(result)), label, owner, site, @@ -231,6 +265,13 @@ pub struct ResultRoot { pub functions: std::ops::Range, } +// What it keeps is a host's result, which may nest at any depth past what the program took of it. +impl Drop for ResultRoot { + fn drop(&mut self) { + std::mem::take(&mut self.value).discard(); + } +} + /// A run's id, shared by its calls and made the first time it is read, when the host gave none. pub(crate) type RunId = Arc>; @@ -322,6 +363,9 @@ pub struct RunHost { pub(crate) promise_like: Option, /// Whether a call interrupted the run. pub interrupted: bool, + /// Set when a host value copied in had an error, whose cause and fields the copy may leave out: the value may then + /// nest past `Limits::max_value_depth`. + pub(crate) partial: bool, /// Moving long stretches of compute to a worker thread, for a run driven as a future. Boxed: the VM's hot fields /// sit after this struct, and a few more bytes here measurably slow its dispatch loop. pub(crate) offload: Option>, @@ -414,6 +458,7 @@ impl RunHost { suggestions: FxHashMap::default(), promise_like: None, interrupted: false, + partial: false, unhandled: Vec::new(), offload: None, modules_loaded: FxHashMap::default(), @@ -649,7 +694,7 @@ pub(crate) fn native(vm: &mut Vm, name: &str, length: u8, f: NativeFn, data: Val pub enum Start { Call, Again, - Wait(Data), + Wait(Kept), } /// A promise was rejected with nothing to handle it: a warning, unless something handles it before the run ends. @@ -693,12 +738,10 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { locate_settled(vm, &e, site, Some(p)); vm.reject(p, e); } - Settlement::Host(settled) => { + Settlement::Host(mut settled) => { + let result = settled.result.take(); let Settled { - result, - label, - owner, - site, + label, owner, site, .. } = *settled; match result { Ok(v) => { @@ -715,6 +758,7 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { Err(HostValue::Interrupt) => interrupt(vm), Err(thrown) => { let e = thrown_value(vm, &thrown, &label, site, Some(p)); + thrown.discard(); vm.reject(p, e); } } @@ -1047,7 +1091,9 @@ fn sync_result( } Returned::Now(Err(thrown)) => { let site = vm.call_offset(); - Err(thrown_value(vm, &thrown, &target.label, site, None)) + let e = thrown_value(vm, &thrown, &target.label, site, None); + thrown.discard(); + Err(e) } Returned::Pending(work) => { let site = vm.call_offset(); @@ -1259,7 +1305,7 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b }; let (d2, phase, waiting) = (d.clone(), data.clone(), durable.clone()); let started: BoxFuture<'static, Result> = match again { - Some(data) => Box::pin(async move { Ok(data) }), + Some(data) => Box::pin(async move { Ok(data.into_inner()) }), None => match &home { None => (d.start)(r.args.clone(), call), Some(home) => { @@ -2001,6 +2047,7 @@ fn error_proto(vm: &mut Vm, name: &str) -> Id { } fn error_from_host(vm: &mut Vm, e: &HostError, label: &str, depth: usize) -> Result { + vm.host.partial = true; let next = |key: &str| format!("{label}.{key}"); let proto = error_proto(vm, e.name.as_str().unwrap_or_default()); let err = vm.make_error(proto, &e.message.to_run_text()); @@ -2345,6 +2392,11 @@ fn result_from_host( value: v, functions: start..end, }); + } else if out.is_err() || vm.host.partial { + // Not copied in whole, it may nest at any depth; copied in whole, it is no deeper than `max_value_depth`, and + // drops as Rust drops it. + vm.host.partial = false; + v.discard(); } out } diff --git a/rust/crates/psychoscript/src/host_function.rs b/rust/crates/psychoscript/src/host_function.rs index 23fc912b..06b6c412 100644 --- a/rust/crates/psychoscript/src/host_function.rs +++ b/rust/crates/psychoscript/src/host_function.rs @@ -319,6 +319,67 @@ pub enum HostValue { Interrupt, } +/// How deep `HostValue::discard` recurses at a time, as `Data::discard`. +const LEVELS: usize = 64; + +impl HostValue { + /// Drops the value recursing at most `LEVELS` deep at a time: a value the host makes may nest deeper than a + /// recursive drop gets on any stack, so what the run drops of the host's, it drops with this. + #[inline(never)] + pub(crate) fn discard(self) { + let mut deeper = Vec::new(); + self.drop_within(LEVELS, &mut deeper); + while let Some(v) = deeper.pop() { + v.drop_within(LEVELS, &mut deeper); + } + } + + /// Drops `levels` levels of the value, leaving what is deeper in `deeper`. + fn drop_within(self, levels: usize, deeper: &mut Vec) { + match self { + v if levels == 0 && v.holds_values() => deeper.push(v), + HostValue::Array(items) => items + .into_iter() + .flatten() + .for_each(|i| i.drop_within(levels - 1, deeper)), + HostValue::Object(fields) => fields + .into_iter() + .for_each(|(_, v)| v.drop_within(levels - 1, deeper)), + HostValue::Map(entries) => entries.into_iter().for_each(|(k, v)| { + k.drop_within(levels - 1, deeper); + v.drop_within(levels - 1, deeper); + }), + HostValue::Set(items) => items + .into_iter() + .for_each(|i| i.drop_within(levels - 1, deeper)), + HostValue::Error(e) | HostValue::Located(e) => { + let HostError { cause, fields, .. } = *e; + if let Some(c) = cause { + (*c).drop_within(levels - 1, deeper); + } + fields + .into_iter() + .for_each(|(_, v)| v.drop_within(levels - 1, deeper)); + } + _ => {} + } + } + + /// Whether it holds other values. + #[inline] + fn holds_values(&self) -> bool { + matches!( + self, + HostValue::Array(_) + | HostValue::Object(_) + | HostValue::Map(_) + | HostValue::Set(_) + | HostValue::Error(_) + | HostValue::Located(_) + ) + } +} + impl HostValue { pub fn object>(fields: impl IntoIterator) -> Self { HostValue::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect()) diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index faa41a6b..ee7cbb14 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -1010,7 +1010,7 @@ impl Enc<'_> { owner, site, } = h.as_ref(); - let (ok, v) = match result { + let (ok, v) = match &**result { Ok(v) => (true, v), Err(v) => (false, v), }; @@ -2901,7 +2901,7 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { vm.host.key(call) ))); } - host::Start::Wait(data_from(at(start, 1)?)?) + host::Start::Wait(crate::data::Kept(data_from(at(start, 1)?)?)) } _ => return Err(invalid("a call in flight is unknown.")), }; diff --git a/rust/crates/psychoscript/tests/value_depth.rs b/rust/crates/psychoscript/tests/value_depth.rs index 2f3bb133..7c931b1c 100644 --- a/rust/crates/psychoscript/tests/value_depth.rs +++ b/rust/crates/psychoscript/tests/value_depth.rs @@ -8,8 +8,8 @@ use std::sync::{Arc, mpsc}; use std::time::Duration; use psychoscript::{ - Data, DurableFunction, HostFunction, HostValue, Limits, MAX_VALUE_DEPTH_LIMIT, ProgramOptions, - RunOutcome, Runtime, Snapshot, from_bytes, to_bytes, + Data, DurableFunction, HostError, HostFunction, HostResult, HostValue, Limits, + MAX_VALUE_DEPTH_LIMIT, ProgramOptions, RunOutcome, Runtime, Snapshot, from_bytes, to_bytes, }; use serde_json::json; @@ -19,6 +19,8 @@ const MOBILE_THREAD: usize = 1 << 20; const HALF: usize = 512 << 10; /// The thread a run moves to past 1 ms of compute: the run's stack budget and room beyond it. const WORKER_THREAD: usize = 768 << 10; +/// Deeper than a recursive drop of a `HostValue` gets on a thread's usual stack. +const DEEPEST: usize = 100_000; /// A program value nested `depth` levels: objects and arrays in turn around a number. fn build(depth: usize) -> String { @@ -360,8 +362,8 @@ fn giving(depth: usize, hold: Arc, given: Option>) } /// What a host call returned is the host's until the program takes it, so a suspend before that saves it however -/// deep it is, and the program meets `Limits::max_value_depth` when it takes it, as it does without a suspend. (A -/// `HostValue` drops recursively, which bounds how deep a run holds one at all, suspended or not.) +/// deep it is, and the program meets `Limits::max_value_depth` when it takes it, as it does without a suspend. The run +/// drops it without recursing, suspended or not. #[test] fn a_result_saved_before_the_program_takes_it_moves_through_bytes() { let code = r#"const p = give(); while (held()) {} try { await p; return "taken" } catch (e) { return String(e) }"#; @@ -370,6 +372,7 @@ fn a_result_saved_before_the_program_takes_it_moves_through_bytes() { MAX_VALUE_DEPTH_LIMIT + 1, 2_000, 5_000, + DEEPEST, ] { let unheld = || Arc::new(AtomicBool::new(false)); let (given, _) = mpsc::channel(); @@ -402,3 +405,83 @@ fn a_result_saved_before_the_program_takes_it_moves_through_bytes() { assert_eq!(outcome.result.unwrap(), expected, "{n}"); } } + +/// Host calls whose value, `depth` deep, the program refuses: returned, thrown, held with functions a suspend keeps it +/// for, by an async function, and by a durable one; and an error whose cause it is. +fn refused(depth: usize) { + let rt = Runtime::make() + .limits(limited(MAX_VALUE_DEPTH_LIMIT)) + .globals(move |_| { + [ + ( + "give", + HostValue::from(HostFunction::new(move |_, _| host(depth))), + ), + ( + "fail", + HostFunction::new(move |_, _| -> HostResult { Err(host(depth)) }).into(), + ), + ( + "kept", + HostFunction::new(move |_, _| { + let f = HostFunction::new(|_, _| HostValue::Undefined); + HostValue::array([f.into(), host(depth)]) + }) + .snapshot(|v| Ok(v.clone()), |v| v) + .into(), + ), + ( + "caused", + HostFunction::new(move |_, _| { + let mut e = HostError::new("deep"); + e.cause = Some(Box::new(host(depth))); + HostValue::Error(Box::new(e)) + }) + .into(), + ), + ( + "later", + HostFunction::new_async(move |_, _| async move { Ok(host(depth)) }).into(), + ), + ( + "job", + DurableFunction::new( + |_, _| async { Ok(Data::Null) }, + move |_, _| async move { Ok(host(depth)) }, + |_, _| async {}, + ) + .into(), + ), + ] + }); + // An error crosses without the cause it can't take. + let outcome = rt.execute("const e = caused(); return [String(e), 'cause' in e]"); + assert_eq!(outcome.json().unwrap(), json!(["Error: deep", false])); + let refusal = format!(" exceeds the maximum value depth of {MAX_VALUE_DEPTH_LIMIT}."); + for call in ["give()", "fail()", "kept()", "await later()", "await job()"] { + let outcome = + rt.execute(format!("try {{ {call} }} catch (e) {{ return String(e) }}").as_str()); + let result = outcome.result.unwrap(); + let message = result.as_string().unwrap().to_string_lossy(); + assert!(message.ends_with(&refusal), "{call}: {message}"); + } +} + +/// What a host call returns or throws is the host's, but the run drops it, without recursing: however deep it is, the +/// program gets its refusal and the process goes on. +#[test] +fn a_result_of_any_depth_is_refused() { + refused(DEEPEST); + refused(1_000_000); +} + +/// A durable call's data restored from bytes is dropped without recursing when the run is dropped before it resumes. +#[test] +fn restored_durable_data_of_any_depth_drops() { + let (waiting, started) = mpsc::channel(); + let rt = holding(0, DEEPEST, true, waiting); + let program = rt.program("return await job()", &ProgramOptions::new()); + let state = from_bytes(&to_bytes(&suspend(program, started))).unwrap(); + let (waiting, _) = mpsc::channel(); + drop(holding(0, 0, false, waiting).resume(&state).unwrap()); +} From 729d9df060148dc006d911e7d9d96d3b07a2e9e3 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 19:41:52 +0100 Subject: [PATCH 2/4] perf(rust): convert a host call's result in place; drop only what the program refused without recursing --- rust/crates/psychoscript/src/host.rs | 70 ++++++++++++++-------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 1ddd09ba..90824c98 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -114,16 +114,9 @@ pub struct Settled { pub site: Option, } -/// A host call's outcome, which the host makes and may nest at any depth: dropped without recursing. Taken out, it -/// leaves `undefined` behind, which holds nothing to drop. -pub struct Held(std::mem::ManuallyDrop); - -impl Held { - #[inline] - pub fn take(&mut self) -> HostResult { - std::mem::replace(&mut *self.0, Ok(HostValue::Undefined)) - } -} +/// A host call's outcome, which the host makes and may nest at any depth: dropped without recursing, unless the program +/// took it (`true`), which leaves nothing deeper than `Limits::max_value_depth`. +pub struct Held(HostResult, bool); impl std::ops::Deref for Held { type Target = HostResult; @@ -136,15 +129,15 @@ impl std::ops::Deref for Held { impl Drop for Held { #[inline] fn drop(&mut self) { - let (Ok(v) | Err(v)) = &mut *self.0; - if !matches!(v, HostValue::Undefined) { - dispose(v); + if !self.1 { + dispose(&mut self.0); } } } #[cold] -fn dispose(v: &mut HostValue) { +fn dispose(r: &mut HostResult) { + let (Ok(v) | Err(v)) = r; std::mem::take(v).discard(); } @@ -156,7 +149,7 @@ impl Settlement { site: Option, ) -> Self { Settlement::Host(Box::new(Settled { - result: Held(std::mem::ManuallyDrop::new(result)), + result: Held(result, false), label, owner, site, @@ -739,26 +732,30 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) { vm.reject(p, e); } Settlement::Host(mut settled) => { - let result = settled.result.take(); let Settled { - label, owner, site, .. - } = *settled; - match result { + result, + label, + owner, + site, + } = &mut *settled; + match &mut result.0 { Ok(v) => { - let v = result_from_host(vm, v, &label, owner.as_deref()); + let v = result_from_host(vm, v, label, owner.as_deref()); match v { - Ok(v) => vm.fulfill(p, v), + Ok(v) => { + result.1 = true; + vm.fulfill(p, v) + } Err(e) => { // The reference converts the value at the call, so its errors point there. - locate_settled(vm, &e, site, Some(p)); + locate_settled(vm, &e, *site, Some(p)); vm.reject(p, e) } } } Err(HostValue::Interrupt) => interrupt(vm), Err(thrown) => { - let e = thrown_value(vm, &thrown, &label, site, Some(p)); - thrown.discard(); + let e = thrown_value(vm, thrown, label, *site, Some(p)); vm.reject(p, e); } } @@ -1083,10 +1080,13 @@ fn sync_result( interrupt(vm); Err(Value::Undef) } - Returned::Now(Ok(v)) => { + Returned::Now(Ok(mut v)) => { let site = vm.call_offset(); - let v = result_from_host(vm, v, &target.label, target.owner.as_deref()) - .inspect_err(|e| locate_at(vm, e, site))?; + let v = result_from_host(vm, &mut v, &target.label, target.owner.as_deref()) + .inspect_err(|e| { + locate_at(vm, e, site); + std::mem::take(&mut v).discard(); + })?; Ok(if f.thenable { promise_like(vm, v) } else { v }) } Returned::Now(Err(thrown)) => { @@ -2367,10 +2367,10 @@ fn response_fn(vm: &mut Vm, f: HostFunction, label: &str, place: &Place) -> Valu } /// A host call's result copied in. When it is saved by an owner's `snapshot` hooks and holds functions, the value is -/// kept so a suspend can save them. +/// kept so a suspend can save them. What is left of a value it refuses may nest at any depth: the caller discards it. fn result_from_host( vm: &mut Vm, - v: HostValue, + v: &mut HostValue, label: &str, owner: Option<&str>, ) -> Result { @@ -2380,7 +2380,7 @@ fn result_from_host( installed: false, within: owner.map(str::to_owned), }; - let out = from_host(vm, &v, label, &place, 0); + let out = from_host(vm, v, label, &place, 0); // The buffers its typed arrays matched are done with. vm.lends.clear(); let end = vm.host.functions.len(); @@ -2389,14 +2389,14 @@ fn result_from_host( { vm.host.results.push(ResultRoot { owner: owner.to_owned(), - value: v, + value: std::mem::take(v), functions: start..end, }); - } else if out.is_err() || vm.host.partial { - // Not copied in whole, it may nest at any depth; copied in whole, it is no deeper than `max_value_depth`, and - // drops as Rust drops it. + } else if vm.host.partial { + // An error copied without parts it couldn't take: it may nest at any depth. Copied in whole, it is no deeper + // than `max_value_depth`, and drops as Rust drops it. vm.host.partial = false; - v.discard(); + std::mem::take(v).discard(); } out } From 2c58d4695da2616b1e85f9e39a4e18818224560e Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 19:48:44 +0100 Subject: [PATCH 3/4] fix(rust): clear the partial flag when a snapshot owner keeps the result --- rust/crates/psychoscript/src/host.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 90824c98..707d6861 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -2392,6 +2392,7 @@ fn result_from_host( value: std::mem::take(v), functions: start..end, }); + vm.host.partial = false; } else if vm.host.partial { // An error copied without parts it couldn't take: it may nest at any depth. Copied in whole, it is no deeper // than `max_value_depth`, and drops as Rust drops it. From e58dac02ae9136414bce5b85a2e88bc682500c53 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Thu, 3 Dec 2026 03:47:13 +0100 Subject: [PATCH 4/4] fix(rust): drop what a namespace listing throws and a function's refused properties without recursing A namespace listing that throws discards what it threw, and a function the program refuses drops its own properties without recursing, sync, async or durable. A thrown value or a global clears the partial flag, and a refused result keeps no root for a later suspend. --- rust/crates/psychoscript/src/host.rs | 32 ++++- rust/crates/psychoscript/src/host_function.rs | 14 ++ rust/crates/psychoscript/tests/value_depth.rs | 133 +++++++++++++++++- 3 files changed, 173 insertions(+), 6 deletions(-) diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index da687f6a..1f14378b 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -662,7 +662,10 @@ fn define_host_global(vm: &mut Vm, name: &str) -> bool { installed: true, within: None, }; - from_host(vm, value, name, &place, 0).unwrap_or(Value::Undef) + let v = from_host(vm, value, name, &place, 0).unwrap_or(Value::Undef); + // The runtime keeps its globals, whole or not. + vm.host.partial = false; + v } }; global(vm, name, v); @@ -786,7 +789,7 @@ fn thrown_value( site: Option, settled: Option, ) -> Value { - match thrown { + let e = match thrown { HostValue::Located(he) => { let proto = error_proto(vm, he.name.as_str().unwrap_or_default()); let e = vm.failure( @@ -814,7 +817,10 @@ fn thrown_value( e } thrown => from_host(vm, thrown, label, &Place::default(), 0).unwrap_or_else(|e| e), - } + }; + // The caller discards what was thrown, whole or not. + vm.host.partial = false; + e } /// Points an error the VM made, not yet located, at a host call's source site. @@ -2418,6 +2424,7 @@ fn result_from_host( let end = vm.host.functions.len(); if let Some(owner) = owner && end > start + && out.is_ok() { vm.host.results.push(ResultRoot { owner: owner.to_owned(), @@ -2469,13 +2476,26 @@ fn own_properties( }; for (k, item) in properties { let path = format!("{label}.{}", k.to_string_lossy()); - let val = from_host(vm, item, &path, &place.child(Some(k)), depth + 1)?; + let val = from_host(vm, item, &path, &place.child(Some(k)), depth + 1) + .inspect_err(|_| shed_properties(vm, id))?; let key = vm.atoms.intern(&k.to_run_text()); vm.define(id, key, val); } Ok(made) } +/// A function whose own properties the program refused keeps none: they may nest at any depth, and the value they came +/// in, which the caller discards, is left their only holder. +#[cold] +fn shed_properties(vm: &mut Vm, id: Id) { + if let Value::Num(index) = vm.native_data(id) { + match &mut vm.host.functions[index as usize].f { + Callee::Fn(f) => f.properties = Arc::new([]), + Callee::Durable(f) => f.properties = Arc::new([]), + } + } +} + /// A host function as a program function, at `label`. A host function made with no name is named by where it is. /// A constructible one is called the same way by `new`. fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option) -> Value { @@ -2787,6 +2807,8 @@ pub(crate) fn namespace_keys(vm: &mut Vm, id: Id) -> Result, Val listed.map_err(|thrown| { let label = vm.ns_label(&ns); let site = vm.call_location(); - thrown_value(vm, &thrown, &label, site, None) + let e = thrown_value(vm, &thrown, &label, site, None); + thrown.discard(); + e }) } diff --git a/rust/crates/psychoscript/src/host_function.rs b/rust/crates/psychoscript/src/host_function.rs index bb1b6ec6..ceb8ef43 100644 --- a/rust/crates/psychoscript/src/host_function.rs +++ b/rust/crates/psychoscript/src/host_function.rs @@ -361,6 +361,8 @@ impl HostValue { .into_iter() .for_each(|(_, v)| v.drop_within(levels - 1, deeper)); } + HostValue::Function(mut f) => drop_properties(&mut f.properties, levels, deeper), + HostValue::Durable(mut f) => drop_properties(&mut f.properties, levels, deeper), _ => {} } } @@ -376,10 +378,22 @@ impl HostValue { | HostValue::Set(_) | HostValue::Error(_) | HostValue::Located(_) + | HostValue::Function(_) + | HostValue::Durable(_) ) } } +/// Drops `levels` levels of a function's own properties, leaving what is deeper in `deeper`, when it is their only +/// holder; others drop them when they're done. +fn drop_properties(properties: &mut Properties, levels: usize, deeper: &mut Vec) { + if let Some(items) = Arc::get_mut(properties) { + items + .iter_mut() + .for_each(|(_, v)| std::mem::take(v).drop_within(levels - 1, deeper)); + } +} + impl HostValue { pub fn object>(fields: impl IntoIterator) -> Self { HostValue::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect()) diff --git a/rust/crates/psychoscript/tests/value_depth.rs b/rust/crates/psychoscript/tests/value_depth.rs index 927ddeec..bd26ff9d 100644 --- a/rust/crates/psychoscript/tests/value_depth.rs +++ b/rust/crates/psychoscript/tests/value_depth.rs @@ -9,7 +9,8 @@ use std::time::Duration; use psychoscript::{ Data, DurableFunction, HostError, HostFunction, HostResult, HostValue, Limits, - MAX_VALUE_DEPTH_LIMIT, ProgramOptions, RunOutcome, Runtime, Snapshot, from_bytes, to_bytes, + MAX_VALUE_DEPTH_LIMIT, Namespace, ProgramOptions, RunOutcome, Runtime, Snapshot, from_bytes, + to_bytes, }; use serde_json::json; @@ -485,3 +486,133 @@ fn restored_durable_data_of_any_depth_drops() { let (waiting, _) = mpsc::channel(); drop(holding(0, 0, false, waiting).resume(&state).unwrap()); } + +/// Whether `call`, caught in a program run by `rt`, throws the refusal of a value past `MAX_VALUE_DEPTH_LIMIT`. +fn refuses(rt: &Runtime, call: &str) { + let outcome = rt.execute(format!("try {{ {call} }} catch (e) {{ return String(e) }}").as_str()); + let result = outcome.result.unwrap(); + let message = result.as_string().unwrap().to_string_lossy(); + let refusal = format!(" exceeds the maximum value depth of {MAX_VALUE_DEPTH_LIMIT}."); + assert!(message.ends_with(&refusal), "{call}: {message}"); +} + +/// What listing a namespace throws is the host's: the run drops it without recursing. +#[test] +fn a_namespace_listing_throws_a_value_of_any_depth() { + let rt = Runtime::make() + .limits(limited(MAX_VALUE_DEPTH_LIMIT)) + .globals(|_| { + [( + "api", + HostValue::from(Namespace::new( + |_| Err(host(DEEPEST)), + |_| HostFunction::new(|_, _| HostValue::Undefined), + )), + )] + }); + refuses(&rt, "Object.keys(api)"); +} + +/// A function with own properties `depth` deep. +fn with_properties(depth: usize) -> HostFunction { + HostFunction::new(|_, _| HostValue::Undefined).properties([("p", host(depth))]) +} + +/// A function a call returns brings its own properties, which the program refuses past the limit: the run drops them +/// without recursing, from a sync, an async and a durable call, and with a durable function. +#[test] +fn a_returned_function_with_properties_of_any_depth_is_refused() { + let rt = Runtime::make() + .limits(limited(MAX_VALUE_DEPTH_LIMIT)) + .globals(|_| { + [ + ( + "give", + HostValue::from(HostFunction::new(|_, _| { + HostValue::from(with_properties(DEEPEST)) + })), + ), + ( + "later", + HostFunction::new_async(|_, _| async { Ok(with_properties(DEEPEST).into()) }) + .into(), + ), + ( + "job", + DurableFunction::new( + |_, _| async { Ok(Data::Null) }, + |_, _| async { Ok(with_properties(DEEPEST).into()) }, + |_, _| async {}, + ) + .into(), + ), + ( + "durable", + HostFunction::new(|_, _| { + let f = DurableFunction::new( + |_, _| async { Ok(Data::Null) }, + |_, _| async { Ok(HostValue::Undefined) }, + |_, _| async {}, + ); + HostValue::from(f.properties([("p", host(DEEPEST))])) + }) + .into(), + ), + ] + }); + for call in ["give()", "await later()", "await job()", "durable()"] { + refuses(&rt, call); + } +} + +/// A runtime whose `kept` returns a function beside a value past the limit, saved by its `snapshot` hooks, and whose +/// `wait` is an idempotent call that says on `started` it started and then waits, or returns at once without it. +fn keeping(started: Option>) -> Runtime { + Runtime::make() + .limits(limited(MAX_VALUE_DEPTH_LIMIT)) + .globals(move |_| { + let started = started.clone(); + [ + ( + "kept", + HostValue::from( + HostFunction::new(|_, _| { + let f = HostFunction::new(|_, _| HostValue::Undefined); + HostValue::array([f.into(), host(MAX_VALUE_DEPTH_LIMIT + 1)]) + }) + .snapshot(|v| Ok(v.clone()), |v| v), + ), + ), + ( + "wait", + HostFunction::new_async(move |_, _| { + let started = started.clone(); + async move { + if let Some(started) = started { + let _ = started.send(()); + std::future::pending::<()>().await; + } + Ok(HostValue::Undefined) + } + }) + .idempotent() + .into(), + ), + ] + }) +} + +/// A result its owner's `snapshot` hooks would save, refused after one of its functions was made: the run keeps +/// nothing of it, so a later suspend saves the run, which resumes. +#[test] +fn a_refused_result_with_functions_leaves_a_suspend_working() { + let (started, ready) = mpsc::channel(); + let code = "let e; try { kept() } catch (x) { e = String(x) } await wait(); return e"; + let program = keeping(Some(started)).program(code, &ProgramOptions::new()); + let state = from_bytes(&to_bytes(&suspend(program, ready))).unwrap(); + let outcome = keeping(None).resume(&state).unwrap().run().unwrap(); + let result = outcome.result.unwrap(); + let message = result.as_string().unwrap().to_string_lossy(); + let refusal = format!(" exceeds the maximum value depth of {MAX_VALUE_DEPTH_LIMIT}."); + assert!(message.ends_with(&refusal), "{message}"); +}