diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..35f29a2a25 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -883,9 +883,10 @@ proptest! { } /// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names, - /// control characters, too long), values, lengths and pointers in and out of its memory runs to - /// an output, never a panic; every call returns a length or a storage code, and the settings and - /// cache of another plug-in in the same store stay as they were. + /// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of + /// its memory runs to an output, or on a small budget to its instruction budget, never a panic; + /// every call returns a length or a storage code, and the settings and cache of another plug-in + /// in the same store stay as they were. #[test] fn hostile_storage_arguments_never_crash( calls in prop::collection::vec( @@ -894,11 +895,12 @@ proptest! { prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x2000)], prop_oneof![any::(), 0..80i32], prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x3000)], - prop_oneof![any::(), 0..5000i32], + prop_oneof![any::(), 0..5000i32, 0..1_100_000i32], ), 0..16, ), key in prop::collection::vec(prop_oneof![Just(b'a'), Just(b'.'), Just(b'/'), Just(b'\\'), Just(b'_'), any::()], 0..80), + fuel in prop::option::of(1_000..200_000u64), ) { use vectorcraft_plugins::host::STORAGE_BUDGET; use vectorcraft_plugins::storage::Meter; @@ -936,17 +938,31 @@ proptest! { .collect(); let text: String = key.iter().map(|b| format!("\\{b:02x}")).collect(); let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::STORAGE_IMPORTS); - let wasm = wat::parse_str(tpl::with_imports(&storing("fuzz.storage"), &imports, &format!("(local $r i32) {body}"), r#"{"objects":[]}"#)).unwrap(); + // 64 more pages hold the values of the large writes. + let wasm = wat::parse_str(tpl::with_imports( + &storing("fuzz.storage"), + &imports, + &format!("(local $r i32) (drop (memory.grow (i32.const 64))) {body}"), + r#"{"objects":[]}"#, + )) + .unwrap(); // A failed case leaves its module installed, and the cases that shrink it install others // under the same id. let r = catch_quiet(|| { s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})) .map_err(|e| e.to_string())?; let p = vectorcraft_plugins::registry::get("fuzz.storage").ok_or("not installed")?; - p.run(b"{\"objects\":[]}", b"{}").map_err(|e| e.to_string()) + // A small budget runs out on the bytes the storage calls move. + let limits = Limits { fuel_base: fuel.unwrap_or(p.limits().fuel_base), fuel_per_byte: 0, ..p.limits().clone() }; + p.run_limited(b"{\"objects\":[]}", b"{}", &limits).map_err(|e| e.to_string()) }); let out = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?; - prop_assert!(out.is_ok(), "{:?}", out); + prop_assert!( + out.is_ok() || (fuel.is_some() && out == Err(Error::Limit("instruction budget".into()).to_string())), + "{:?} on {:?} instructions", + out, + fuel + ); prop_assert_eq!(theirs.setting("mine", m).unwrap(), Some(b"kept".to_vec())); prop_assert_eq!(theirs.cache_entry("mine", m).unwrap(), Some(b"kept".to_vec())); prop_assert_eq!(theirs.cache_bytes(), 4); diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index b98407cb7c..354610e4c0 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -97,6 +97,10 @@ pub const MAX_STORAGE_CALLS: usize = 10_000; /// pass it returns [`STORAGE_BUDGET`]. pub const MAX_STORAGE_BYTES: usize = 1 << 30; +/// Bytes a storage call reads or writes for each instruction it costs the run, counted as for +/// [`MAX_STORAGE_BYTES`]: the 1 GiB a run may move costs 16,777,216 instructions. +pub const STORAGE_BYTES_PER_FUEL: u64 = 64; + /// What `vc_call` returns: the command ran, and `vc_call_result` reads its result. pub const CALL_OK: i32 = 0; /// What `vc_call` or `vc_call_result` returns: the id, the arguments or the buffer doesn't lie @@ -163,6 +167,19 @@ impl std::fmt::Display for CallPending { impl wasmi::errors::HostError for CallPending {} +/// What a storage call ends the run with when the instructions it may take can't pay for its bytes +/// ([`STORAGE_BYTES_PER_FUEL`]); the host reports why ([`Run::storage_stop`]). +#[derive(Debug)] +pub(crate) struct StorageStop; + +impl std::fmt::Display for StorageStop { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("storage call") + } +} + +impl wasmi::errors::HostError for StorageStop {} + /// One host import: its name, its type and the permission it needs. pub struct Import { pub name: &'static str, @@ -365,6 +382,18 @@ pub(crate) struct Run { storage: Option>, storage_calls: usize, storage_bytes: usize, + /// The instructions of the call's budget not yet handed to the store, which storage calls also + /// pay from; the host keeps it up to date around each slice. + pub(crate) fuel_left: u64, + /// Bytes storage reads copied into the module's memory beyond the bytes the storage counted for + /// them, such as a settings value answered from memory; they cost instructions at the same rate. + copied_bytes: u64, + /// Instructions the last storage call cost ([`STORAGE_BYTES_PER_FUEL`]), still to be taken. + fuel_owed: u64, + /// Why the call ends after a storage call: the instruction budget when it needed more + /// instructions than it could take, or the deadline or Cancel, checked before a storage call + /// takes from [`Run::fuel_left`] and after every storage call. + pub(crate) storage_stop: Option, /// The commands `vc_call` may run (the manifest's `commandAllowlist`), once the module has /// loaded and when the run has something to run them ([`Run::allow_calls`]); `None` otherwise. allowed: Option>, @@ -395,6 +424,10 @@ impl Run { storage: None, storage_calls: 0, storage_bytes: 0, + fuel_left: 0, + copied_bytes: 0, + fuel_owed: 0, + storage_stop: None, allowed: None, calls: 0, call_bytes: 0, @@ -527,16 +560,48 @@ impl Run { /// Makes one storage call with `call`, on the plug-in's storage and a [`Meter`] holding the /// run's storage bytes left, and counts the call and the bytes it read and wrote → the code for /// a run that has used up its calls or has no storage, else what `call` returns. - fn metered(&mut self, call: impl FnOnce(&dyn Storage, &mut Meter) -> std::result::Result) -> std::result::Result { + /// + /// The run's storage bytes cost one instruction for each whole [`STORAGE_BYTES_PER_FUEL`] + /// bytes, counted over the run, so splitting a transfer into calls costs the same. The meter + /// also holds no more bytes than the `held` instructions in the store pay for, with + /// [`Run::fuel_left`] too while the deadline and Cancel have not come ([`Meter::gated`]), so + /// the call stops before a read or write they can't pay for; one the storage bytes left would + /// allow sets [`Run::storage_stop`]. What the call costs goes to [`Run::fuel_owed`]. + fn metered( + &mut self, + held: u64, + call: impl FnOnce(&dyn Storage, &mut Meter) -> std::result::Result, + ) -> std::result::Result { if self.storage_calls >= MAX_STORAGE_CALLS { return Err(STORAGE_BUDGET); } self.storage_calls += 1; let Some(store) = self.storage.clone() else { return Err(STORAGE_UNAVAILABLE) }; - let mut meter = Meter::new(MAX_STORAGE_BYTES.saturating_sub(self.storage_bytes) as u64); + let before = self.storage_bytes as u64; + let by_bytes = MAX_STORAGE_BYTES.saturating_sub(self.storage_bytes) as u64; + // Bytes up to the end of the last whole unit `fuel` instructions pay for. + let by_fuel = |fuel: u64| { + let units = (before / STORAGE_BYTES_PER_FUEL).saturating_add(fuel).saturating_add(1); + units.saturating_mul(STORAGE_BYTES_PER_FUEL).saturating_sub(before).saturating_sub(1) + }; + // Bytes past what the store's fuel pays for are read or written only before the deadline + // and Cancel, as the host hands out the rest of the budget only then. + let left = by_bytes.min(by_fuel(held.saturating_add(self.fuel_left))); + let mut meter = Meter::gated(left, by_fuel(held), self.deadline.at); let done = call(store.as_ref(), &mut meter); // What the call read before it failed counts too. self.storage_bytes = self.storage_bytes.saturating_add(usize::try_from(meter.used()).unwrap_or(usize::MAX)); + self.fuel_owed = (self.storage_bytes as u64 / STORAGE_BYTES_PER_FUEL).saturating_sub(before / STORAGE_BYTES_PER_FUEL); + // A read or write the run's storage bytes alone allow was refused for its instructions, or + // for the deadline or Cancel. + let refused = meter.refused(); + if matches!(done, Err(StorageError::Budget)) && refused > 0 && refused <= by_bytes.saturating_sub(meter.used()) { + self.storage_stop = Some(match meter.stopped() { + Some(storage::Gate::Cancel) => Error::Cancelled, + Some(storage::Gate::Deadline) => Error::Limit(TIME_BUDGET.into()), + None => Error::Limit("instruction budget".into()), + }); + } done.map_err(|e| storage_code(&e)) } @@ -549,8 +614,8 @@ impl Run { } /// `vc_settings_get` and `vc_cache_read`: copies the value of the key at `name` into the - /// `out_cap` bytes at `out` when it fits → its length. - fn storage_read(&mut self, area: Area, memory: &mut [u8], name: (usize, usize), out: (usize, usize)) -> i32 { + /// `out_cap` bytes at `out` when it fits → its length. The store holds `held` instructions. + fn storage_read(&mut self, area: Area, memory: &mut [u8], name: (usize, usize), out: (usize, usize), held: u64) -> i32 { let key = match Self::storage_name(memory, name.0, name.1) { Ok(key) => key, Err(code) => return code, @@ -559,7 +624,8 @@ impl Run { return STORAGE_OUTSIDE_MEMORY; } // The storage counts what it read whether or not the value fits the buffer. - let got = self.metered(|store, meter| match area { + let counted = self.storage_bytes; + let got = self.metered(held, |store, meter| match area { Area::Settings => store.setting(&key, meter), Area::Cache => store.cache_entry(&key, meter), }); @@ -573,12 +639,18 @@ impl Run { && let Some(dest) = memory.get_mut(out.0..out.0 + value.len()) { dest.copy_from_slice(&value); + // Bytes copied that the storage didn't count, counted over the run like the others. + let uncounted = (value.len() as u64).saturating_sub(self.storage_bytes.saturating_sub(counted) as u64); + let before = self.copied_bytes / STORAGE_BYTES_PER_FUEL; + self.copied_bytes = self.copied_bytes.saturating_add(uncounted); + self.fuel_owed = self.fuel_owed.saturating_add(self.copied_bytes / STORAGE_BYTES_PER_FUEL - before); } len } - /// `vc_settings_set` and `vc_cache_write`: sets the key at `name` to the `value` bytes. - fn storage_write(&mut self, area: Area, memory: &[u8], name: (usize, usize), value: (usize, usize)) -> i32 { + /// `vc_settings_set` and `vc_cache_write`: sets the key at `name` to the `value` bytes. The + /// store holds `held` instructions. + fn storage_write(&mut self, area: Area, memory: &[u8], name: (usize, usize), value: (usize, usize), held: u64) -> i32 { let key = match Self::storage_name(memory, name.0, name.1) { Ok(key) => key, Err(code) => return code, @@ -587,7 +659,7 @@ impl Run { if bytes.len() > area.max_value() { return STORAGE_FULL; } - let written = self.metered(|store, meter| match area { + let written = self.metered(held, |store, meter| match area { Area::Settings => store.set_setting(&key, bytes, meter), Area::Cache => store.set_cache_entry(&key, bytes, meter), }); @@ -595,8 +667,8 @@ impl Run { } /// `vc_settings_delete` and `vc_cache_clear`: removes the key at `name`, or with `vc_cache_clear` - /// and a `name` of no bytes, every cache entry. - fn storage_remove(&mut self, area: Area, memory: &[u8], name: (usize, usize)) -> i32 { + /// and a `name` of no bytes, every cache entry. The store holds `held` instructions. + fn storage_remove(&mut self, area: Area, memory: &[u8], name: (usize, usize), held: u64) -> i32 { let key = match (area, name.1) { (Area::Cache, 0) => None, _ => match Self::storage_name(memory, name.0, name.1) { @@ -604,7 +676,7 @@ impl Run { Err(code) => return code, }, }; - let removed = self.metered(|store, meter| match (area, key) { + let removed = self.metered(held, |store, meter| match (area, key) { (Area::Settings, Some(key)) => store.delete_setting(&key, meter), (Area::Cache, Some(key)) => store.remove_cache_entry(&key), (_, None) => store.clear_cache().map(|_| true), @@ -700,6 +772,35 @@ fn memory_and_host<'a>(caller: &'a mut Caller<'_, Host>) -> Option<(&'a mut [u8] Some(memory.data_and_store_mut(caller)) } +/// Takes what the last storage call cost ([`Run::fuel_owed`]) from the `held` instructions in the +/// store, then from [`Run::fuel_left`]. A call that needed more instructions than those, or that +/// ended after the deadline or Cancel (checked in that order, as after a `vc_call`), ends the run +/// with [`StorageStop`] and the reason in [`Run::storage_stop`]. +fn pay_storage(caller: &mut Caller<'_, Host>, held: u64) -> std::result::Result<(), wasmi::Error> { + let run = &mut caller.data_mut().run; + let owed = std::mem::take(&mut run.fuel_owed); + if run.storage_stop.is_none() { + run.storage_stop = if owed > held.saturating_add(run.fuel_left) { + Some(Error::Limit("instruction budget".into())) + } else if run.deadline.passed() { + Some(Error::Limit(TIME_BUDGET.into())) + } else if vectorcraft_doc::cancel::is_cancelled() { + Some(Error::Cancelled) + } else { + None + }; + } + if run.storage_stop.is_some() { + return Err(wasmi::Error::host(StorageStop)); + } + let from_store = owed.min(held); + run.fuel_left = run.fuel_left.saturating_sub(owed - from_store); + if from_store > 0 { + caller.set_fuel(held - from_store)?; + } + Ok(()) +} + /// An i32 argument as the unsigned offset or length it stands for. fn offset(v: i32) -> usize { v as u32 as usize @@ -726,18 +827,34 @@ pub(crate) fn linker(engine: &Engine, granted: &[Permission]) -> Linker { if !granted.contains(&permission) { continue; } - let _ = linker.func_wrap(MODULE, get, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, out: i32, out_cap: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_read(area, data, (offset(key), offset(key_len)), (offset(out), offset(out_cap))) - }); - let _ = linker.func_wrap(MODULE, set, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, value: i32, value_len: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_write(area, data, (offset(key), offset(key_len)), (offset(value), offset(value_len))) - }); - let _ = linker.func_wrap(MODULE, remove, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_remove(area, data, (offset(key), offset(key_len))) - }); + // A storage call pays for its bytes before it returns ([`pay_storage`]). + let _ = linker.func_wrap( + MODULE, + get, + move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, out: i32, out_cap: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_read(area, data, (offset(key), offset(key_len)), (offset(out), offset(out_cap)), held); + pay_storage(&mut caller, held).map(|()| code) + }, + ); + let _ = linker.func_wrap( + MODULE, + set, + move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, value: i32, value_len: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_write(area, data, (offset(key), offset(key_len)), (offset(value), offset(value_len)), held); + pay_storage(&mut caller, held).map(|()| code) + }, + ); + let _ = + linker.func_wrap(MODULE, remove, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_remove(area, data, (offset(key), offset(key_len)), held); + pay_storage(&mut caller, held).map(|()| code) + }); } if granted.contains(&Permission::Commands) { // A call that can be made pauses the run: the host makes it with what the run was given to diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 1a25e9e6b0..7c4262dd4e 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -191,6 +191,27 @@ fn charge(live: &mut Live, left: &mut u64, cost: u64) -> Result<()> { live.store.set_fuel(held - (cost - from_left)).map_err(wasm_err) } +/// Resumes a run's call with `step`: the store's storage calls may also pay from `left` +/// ([`host::Run::fuel_left`]), and what they took from it comes off `left` when the call pauses → +/// the pause, or the error the call ended with ([`run_err`]). +fn slice(live: &mut Live, left: &mut u64, step: impl FnOnce(&mut Store) -> std::result::Result) -> Result { + live.store.data_mut().run.fuel_left = *left; + let paused = step(&mut live.store); + *left = std::mem::take(&mut live.store.data_mut().run.fuel_left); + paused.map_err(|e| run_err(&mut live.store, e)) +} + +/// Why a storage call ended a run of `store` ([`host::Run::storage_stop`]). +fn stop_reason(store: &mut Store) -> Error { + store.data_mut().run.storage_stop.take().unwrap_or_else(|| Error::Limit("instruction budget".into())) +} + +/// The error `e` that a run of `store` ended with: a storage call's reason ([`host::StorageStop`]) +/// or [`wasm_err`]'s. +fn run_err(store: &mut Store, e: wasmi::Error) -> Error { + if e.downcast_ref::().is_some() { stop_reason(store) } else { wasm_err(e) } +} + fn wasm_err(e: wasmi::Error) -> Error { if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) } } @@ -306,7 +327,7 @@ impl Plugin { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); - return Err(wasm_err(e)); + return Err(run_err(&mut store, e)); } }; let memory = @@ -321,7 +342,9 @@ impl Plugin { /// for it. It charges a `memory.fill` or `memory.copy` for its whole length before writing, so /// up to that cost can be left in the store at a pause. Each slice tops the store up to the /// slice size, keeping that fuel, and a run ends with the instruction budget only when the - /// store's fuel and the rest of the budget together can't pay for the next instruction. + /// store's fuel and the rest of the budget together can't pay for the next instruction. A + /// storage call pays for its bytes ([`host::STORAGE_BYTES_PER_FUEL`]) from the store's fuel and + /// the rest of the budget as it is made, and one they can't pay for ends the run. fn call(&self, live: &mut Live, f: &TypedFunc, params: P, fuel: u64, deadline: &Deadline) -> Result { self.call_with(live, f, params, fuel, deadline, None) } @@ -343,11 +366,14 @@ impl Plugin { let give = left.min(FUEL_SLICE); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; - let mut call = f.call_resumable(&mut live.store, params).map_err(wasm_err)?; + let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?; loop { match call { TypedResumableCall::Finished(r) => return Ok(r), TypedResumableCall::HostTrap(inv) => { + if inv.host_error().downcast_ref::().is_some() { + return Err(stop_reason(&mut live.store)); + } let pending = live.store.data_mut().run.pending.take(); let (Some((id, args, size)), Some(bridge)) = (pending, bridge.as_deref_mut()) else { return Err(Error::Trap("unexpected host trap".into())); @@ -361,7 +387,7 @@ impl Plugin { charge(live, &mut left, returned as u64 / 64)?; deadline.check()?; vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; - call = inv.resume(&mut live.store, &[Val::I32(code)]).map_err(wasm_err)?; + call = slice(live, &mut left, |store| inv.resume(store, &[Val::I32(code)]))?; } TypedResumableCall::OutOfFuel(inv) => { let need = inv.required_fuel(); @@ -375,7 +401,7 @@ impl Plugin { let fill = total.min(FUEL_SLICE.max(need)).max(held); left -= fill - held; live.store.set_fuel(fill).map_err(wasm_err)?; - call = inv.resume(&mut live.store).map_err(wasm_err)?; + call = slice(live, &mut left, |store| inv.resume(store))?; } } } diff --git a/crates/plugins/src/storage.rs b/crates/plugins/src/storage.rs index b7de23c45a..fb32e94513 100644 --- a/crates/plugins/src/storage.rs +++ b/crates/plugins/src/storage.rs @@ -49,12 +49,33 @@ pub enum StorageError { pub struct Meter { left: u64, used: u64, + refused: u64, + /// Past `free` bytes in all, a read or write happens only before the deadline `until` and + /// Cancel ([`vectorcraft_doc::cancel`]); `stopped` records which refused one. + free: u64, + until: Option, + stopped: Option, +} + +/// What made a gated [`Meter`] refuse a read or write. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Gate { + /// The run was canceled. + Cancel, + /// The run's deadline passed. + Deadline, } impl Meter { /// A meter that lets a call read and write `left` bytes. pub fn new(left: u64) -> Self { - Meter { left, used: 0 } + Meter { left, used: 0, refused: 0, free: u64::MAX, until: None, stopped: None } + } + + /// A meter that lets a call read and write `left` bytes, those past the first `free` only + /// before `until` and Cancel. + pub(crate) fn gated(left: u64, free: u64, until: web_time::Instant) -> Self { + Meter { free, until: Some(until), ..Meter::new(left) } } /// A meter with no limit, for callers that don't count. @@ -63,20 +84,46 @@ impl Meter { } /// Counts `bytes` about to be read or written → [`StorageError::Budget`], counting nothing, - /// when that is more than is left. + /// when that is more than is left, or when they pass the free bytes of a gated meter after its + /// deadline or Cancel. pub fn take(&mut self, bytes: u64) -> Result<(), StorageError> { if bytes > self.left { + self.refused = bytes; return Err(StorageError::Budget); } + if self.used.saturating_add(bytes) > self.free { + // The deadline first, as the host checks it between two slices. + let closed = if self.until.is_some_and(|at| web_time::Instant::now() >= at) { + Some(Gate::Deadline) + } else { + vectorcraft_doc::cancel::is_cancelled().then_some(Gate::Cancel) + }; + if closed.is_some() { + self.stopped = closed; + self.refused = bytes; + return Err(StorageError::Budget); + } + } self.left -= bytes; self.used = self.used.saturating_add(bytes); Ok(()) } + /// What made the meter refuse a read or write past its free bytes ([`Meter::gated`]), if + /// anything did. + pub(crate) fn stopped(&self) -> Option { + self.stopped + } + /// The bytes counted so far. pub fn used(&self) -> u64 { self.used } + + /// The bytes of the last read or write the meter refused (0 when it refused none). + pub(crate) fn refused(&self) -> u64 { + self.refused + } } impl std::fmt::Display for StorageError { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index ae99846c69..f4cb2e103b 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -621,9 +621,9 @@ fn charged( key: &str, meter: &mut Meter, ) -> Result>, StorageError> { - let value = kept.lock().unwrap().get(key).cloned(); - meter.take(value.as_ref().map_or(0, |v| v.len() as u64))?; - Ok(value) + let kept = kept.lock().unwrap(); + meter.take(kept.get(key).map_or(0, |v| v.len() as u64))?; + Ok(kept.get(key).cloned()) } impl Storage for Kept { @@ -777,6 +777,224 @@ fn a_read_into_too_small_a_buffer_still_counts_its_bytes() { registry::set_storage(id, None); } +/// Storage calls cost the run one instruction for every 64 bytes they read or write: reading a +/// 64 MiB cache entry, or writing 1 MiB to the cache 64 times, ends a run of 1 M instructions with +/// its instruction budget and finishes within 2 M. A call the run can't pay for reads and writes +/// nothing, a call pays from the budget not yet in the store, a call past the 1 GiB still returns +/// `STORAGE_BUDGET`, and a small read finishes on a small budget. +#[test] +fn storage_calls_pay_instructions_for_the_bytes_they_move() { + use vectorcraft_plugins::host::{MAX_STORAGE_BYTES, STORAGE_BUDGET, STORAGE_DONE}; + use vectorcraft_plugins::storage::MAX_CACHE_ENTRY; + let id = "test.storage.fuel"; + let kept = std::sync::Arc::new(Kept::default()); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + kept.settings.lock().unwrap().insert("zoom".into(), b"hello".to_vec()); + registry::set_storage(id, Some(kept.clone())); + let run = |first: &str, fuel_base: u64| { + let limits = Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }; + Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), first, INPUT)), limits).unwrap().run(INPUT.as_bytes(), b"{}") + }; + let zoom = "(i32.const 0x2000) (i32.const 4)"; + let reading = expect(&format!("(call $vc_cache_read {zoom} (i32.const 0x3000) (i32.const 0))"), MAX_CACHE_ENTRY as i32); + // 17 more pages of memory, then 1 MiB of them written to the cache 64 times. + let write = expect(&format!("(call $vc_cache_write {zoom} (i32.const 0x20000) (i32.const 1048576))"), STORAGE_DONE); + let writing = format!( + "(local $n i32) (drop (memory.grow (i32.const 17))) (local.set $n (i32.const 64)) \ + (loop $work {write} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ); + let budget = Err(Error::Limit("instruction budget".into())); + let done = Ok(INPUT.as_bytes().to_vec()); + let small = expect(&format!("(call $vc_settings_get {zoom} (i32.const 0x3000) (i32.const 16))"), 5); + assert_eq!(run(&small, 10_000), done, "a small read on 10,000 instructions"); + // Growing the memory by 17 pages costs about 17,400 instructions and writing 1 MiB 16,384: a + // write the run can't pay for writes nothing. + let once = format!("(drop (memory.grow (i32.const 17))) {write}"); + assert_eq!(run(&once, 30_000), budget, "1 MiB written on 30,000 instructions"); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged"); + assert_eq!(run(&once, 60_000), done, "1 MiB written on 60,000 instructions"); + assert_eq!(kept.cache_bytes(), 1 << 20, "the entry is written"); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + assert_eq!(run(&reading, 1_000_000), budget, "a 64 MiB read on 1 M instructions"); + assert_eq!(run(&reading, 2_000_000), done, "a 64 MiB read on 2 M instructions"); + assert_eq!(run(&writing, 1_000_000), budget, "64 MiB written on 1 M instructions"); + assert_eq!(run(&writing, 2_000_000), done, "64 MiB written on 2 M instructions"); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + // About 19.7 M instructions of fills leave less of the first 20 M slice than a 64 MiB read + // costs; the read pays from the rest of the budget. + let burning = format!( + "(local $n i32) (drop (memory.grow (i32.const 130))) (local.set $n (i32.const 149)) \ + (loop $burn (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $burn (local.get $n))) {reading}" + ); + assert_eq!(run(&burning, 21_000_000), done, "a read across two slices within the budget"); + assert_eq!(run(&burning, 20_500_000), budget, "a read across two slices over the budget"); + // What the read took from the rest of the budget is gone: six more 8 MiB fills (about 786,000 + // instructions) don't fit the 21 M. + let more = format!( + "{burning} (local.set $n (i32.const 6)) (loop $more (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $more (local.get $n)))" + ); + assert_eq!(run(&more, 21_000_000), budget, "fills after the read over the budget"); + // With 8 MiB of the run's 1 GiB of storage bytes left and instructions for less, a 64 MiB read + // returns `STORAGE_BUDGET`, since the bytes alone refuse it, and the run goes on. + let rest = MAX_STORAGE_BYTES - 15 * MAX_CACHE_ENTRY - (8 << 20); + kept.cache.lock().unwrap().insert("x".into(), vec![0; rest]); + let x = expect("(call $vc_cache_read (i32.const 0x200d) (i32.const 1) (i32.const 0x3000) (i32.const 0))", rest as i32); + let over = expect(&format!("(call $vc_cache_read {zoom} (i32.const 0x3000) (i32.const 0))"), STORAGE_BUDGET); + let near = [vec![reading.clone(); 15], vec![x, over]].concat().concat(); + assert_eq!(run(&near, 16_700_000), done, "a read past the 1 GiB"); + // Bytes are counted over the run: 9,000 writes of 63 bytes, each under 64, cost about 8,860 + // instructions more than 9,000 writes of none, not 0 or 9,000 as rounding each write down or up + // would. Each run's fewest instructions are found by bisection. + let looped = |len: u32| { + let write = expect(&format!("(call $vc_cache_write {zoom} (i32.const 0x2000) (i32.const {len}))"), STORAGE_DONE); + format!( + "(local $n i32) (local.set $n (i32.const 9000)) \ + (loop $work {write} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ) + }; + let fewest = |first: &str| { + let (mut lo, mut hi) = (10_000, 50_000_000); + assert_eq!(run(first, hi), done, "the writes finish"); + while lo + 1 < hi { + let mid = (lo + hi) / 2; + match run(first, mid) { + Ok(_) => hi = mid, + Err(Error::Limit(why)) if why == "instruction budget" => lo = mid, + Err(e) => panic!("the writes failed on {mid} instructions: {e:?}"), + } + } + hi + }; + let (none, small) = (fewest(&looped(0)), fewest(&looped(63))); + assert!((none + 8_800..=none + 8_900).contains(&small), "63-byte writes take {small} instructions, empty ones {none}"); + registry::set_storage(id, None); +} + +/// A storage call that needs more of the budget than the store holds takes it only before Cancel +/// and the deadline: after either, a 32 MiB write near the end of the first 20 M slice writes +/// nothing and the run ends as canceled or with its time budget. +#[test] +fn after_cancel_or_the_deadline_a_storage_call_takes_no_more_of_the_budget() { + use vectorcraft_plugins::host::STORAGE_DONE; + use vectorcraft_plugins::storage::MAX_CACHE_ENTRY; + let id = "test.storage.cancel"; + let kept = std::sync::Arc::new(Kept::default()); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + registry::set_storage(id, Some(kept.clone())); + // Growing by 512 pages and 148 fills of 8 MiB take about 19.9 M instructions; the write costs + // 524,288. + let write = expect("(call $vc_cache_write (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 33554432))", STORAGE_DONE); + let first = format!( + "(local $n i32) (drop (memory.grow (i32.const 512))) (local.set $n (i32.const 148)) \ + (loop $burn (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $burn (local.get $n))) {write}" + ); + let limits = Limits { fuel_base: 21_000_000, fuel_per_byte: 0, ..Limits::default() }; + let p = Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), limits.clone()).unwrap(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); + assert_eq!(r, Err(Error::Cancelled)); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged"); + let timed = Limits { wall_time_ms: 0, ..limits }; + assert_eq!(p.run_limited(INPUT.as_bytes(), b"{}", &timed), Err(Error::Limit("time budget".into()))); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged after the deadline"); + // With both, the time budget, as between two slices. + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run_limited(INPUT.as_bytes(), b"{}", &timed)); + assert_eq!(r, Err(Error::Limit("time budget".into()))); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Ok(INPUT.as_bytes().to_vec()), "the same run without Cancel"); + assert_eq!(kept.cache_bytes(), 32 << 20, "the entry is written"); + registry::set_storage(id, None); +} + +/// The host checks the deadline and Cancel after every storage call, also one the store's +/// instructions pay for: after either, a 1 MiB cache write is the run's last storage call, and the +/// write after it doesn't happen. +#[test] +fn a_run_past_its_deadline_or_canceled_stops_after_a_storage_call() { + use vectorcraft_plugins::host::STORAGE_DONE; + let id = "test.storage.after"; + let kept = std::sync::Arc::new(Kept::default()); + registry::set_storage(id, Some(kept.clone())); + let first = format!( + "(drop (memory.grow (i32.const 17))) {} {}", + expect("(call $vc_cache_write (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 1048576))", STORAGE_DONE), + expect("(call $vc_cache_write (i32.const 0x200d) (i32.const 1) (i32.const 0x20000) (i32.const 1048576))", STORAGE_DONE), + ); + let p = Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), Limits::default()).unwrap(); + let written = || { + let cache = kept.cache.lock().unwrap(); + let names = (cache.contains_key("zoom"), cache.contains_key("x")); + drop(cache); + kept.cache.lock().unwrap().clear(); + names + }; + let timed = Limits { wall_time_ms: 0, ..p.limits().clone() }; + assert_eq!(p.run_limited(INPUT.as_bytes(), b"{}", &timed), Err(Error::Limit("time budget".into()))); + assert_eq!(written(), (true, false), "after the deadline"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + assert_eq!(vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")), Err(Error::Cancelled)); + assert_eq!(written(), (true, false), "after Cancel"); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Ok(INPUT.as_bytes().to_vec()), "the same run before both"); + assert_eq!(written(), (true, true), "before both"); + registry::set_storage(id, None); +} + +/// A store that answers every setting with the same value without counting its bytes, as the app's +/// store answers a get from the settings it keeps in memory. +struct Remembered(Vec); + +impl Storage for Remembered { + fn setting(&self, _: &str, _: &mut Meter) -> Result>, StorageError> { + Ok(Some(self.0.clone())) + } + fn set_setting(&self, _: &str, _: &[u8], _: &mut Meter) -> Result<(), StorageError> { + Ok(()) + } + fn delete_setting(&self, _: &str, _: &mut Meter) -> Result { + Ok(false) + } + fn cache_entry(&self, _: &str, _: &mut Meter) -> Result>, StorageError> { + Ok(None) + } + fn set_cache_entry(&self, _: &str, _: &[u8], _: &mut Meter) -> Result<(), StorageError> { + Ok(()) + } + fn remove_cache_entry(&self, _: &str) -> Result { + Ok(false) + } + fn clear_cache(&self) -> Result { + Ok(0) + } + fn cache_bytes(&self) -> u64 { + 0 + } +} + +/// A settings get the store answers without counting bytes still costs the bytes it copies into +/// the module's memory: 2,000 gets of a 64 KiB value (128,000 KiB copied) end a run of 1 M +/// instructions with its instruction budget and finish within 4 M. +#[test] +fn settings_gets_answered_from_memory_pay_for_the_bytes_they_copy() { + let id = "test.storage.copied"; + registry::set_storage(id, Some(std::sync::Arc::new(Remembered(vec![7; 65536])))); + let get = expect("(call $vc_settings_get (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 65536))", 65536); + let first = format!( + "(local $n i32) (drop (memory.grow (i32.const 2))) (local.set $n (i32.const 2000)) \ + (loop $work {get} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ); + let run = |fuel_base: u64| { + let limits = Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }; + Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), limits).unwrap().run(INPUT.as_bytes(), b"{}") + }; + assert_eq!(run(1_000_000), Err(Error::Limit("instruction budget".into())), "on 1 M instructions"); + assert_eq!(run(4_000_000), Ok(INPUT.as_bytes().to_vec()), "on 4 M instructions"); + registry::set_storage(id, None); +} + /// A plug-in reaches only the storage of its own id, and a plug-in with none (not installed with a /// plug-in store, as on the web) gets `STORAGE_UNAVAILABLE`. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 7e6dd26185..ab294db1ff 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -129,14 +129,14 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | -| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte; [storage calls](#settings-and-cache) take one more for every 64 bytes they move | `Limit("instruction budget")` | +| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions and after each [storage call](#settings-and-cache); the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | | Module shape | wasmi's strict limits (≤ 10,000 functions, 1 memory, …) | rejected | An export runs where the export runs: with Background Export on, on the export's worker, whose Cancel stops the -plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the +plug-in between two of those 20 M-instruction slices or after a storage call; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. ### Instruction budget preference @@ -151,7 +151,7 @@ and MCP alike: A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and -the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +the time budget stop a run between two 20 M-instruction slices, or after a storage call, with either choice. `prefs.set {key: "pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other value; a saved preferences file with another value reads as Normal. @@ -428,6 +428,14 @@ its 10,000 storage calls or its 1 GiB of storage reads and writes. Each call cou settings call counts the whole settings file when it reads the file, and a set or delete also counts the whole file when it writes the file; a cache call counts the entry it reads or writes. A read counts them even when the value doesn't fit and nothing is copied. A call that would pass the 1 GiB returns `-7` before it reads or writes anything. +The bytes the calls count also cost the run one instruction of its budget for every 64 bytes (VectorCraft's own +value), counted over the whole run, so the 1 GiB costs about 16.8 M instructions. A get also pays at that rate for the +bytes it copies into the module's memory that it didn't count, such as a value answered from memory. A call stops +before a read or write of a file that the run's instructions can't pay for, and the run ends with +`Limit("instruction budget")`; a set or delete may already have read the settings file then. A call takes +instructions beyond the current 20 M-instruction slice only before Cancel and the time budget; after either, a read or +write that needs them doesn't happen. After every storage call the run checks its time budget and Cancel, and stops +if either has come. A read or write that would pass the 1 GiB still returns `-7`, whatever the instructions left. The app keeps the settings in memory after the first call and reads `settings.json` again only when the file's size or modified time differs from the last read or write. A get answered from memory reads no file and counts no bytes. A