sansmoraxz opened issue #15105:
Test Case
component.wat: a component exportingecho: func(data: list<u8>) -> list<u8>, which hands the list back, andlen: func(data: list<u8>) -> u32, which only lowers it.;; `echo` hands the list back; `len` returns its length (isolates lowering). ;; `realloc` always returns offset 16 (one allocation per call), growing memory as needed. (component (core module $m (memory (export "memory") 1) (func (export "realloc") (param i32 i32 i32 i32) (result i32) (local $pages i32) (local.set $pages (i32.shr_u (i32.add (local.get 3) (i32.const 65551)) (i32.const 16))) (if (i32.gt_u (local.get $pages) (memory.size)) (then (drop (memory.grow (i32.sub (local.get $pages) (memory.size)))))) (i32.const 16)) (func (export "echo") (param i32 i32) (result i32) (i32.store (i32.const 0) (local.get 0)) (i32.store (i32.const 4) (local.get 1)) (i32.const 0)) (func (export "len") (param i32 i32) (result i32) (local.get 1))) (core instance $i (instantiate $m)) (func (export "echo") (param "data" (list u8)) (result (list u8)) (canon lift (core func $i "echo") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))) (func (export "len") (param "data" (list u8)) (result u32) (canon lift (core func $i "len") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))))The host program calls both exports with 1, 16 and 64 MiB lists, dynamically (
Func::call_asyncwithVal::List, as an embedder that only learns signatures at runtime must) and throughTypedFunc<(Vec<u8>,), _>, and prints each call's time and how far peak RSS rose during it.
Cargo.toml:[package] name = "wasmtime-val-list-repro" version = "0.1.0" edition = "2024" [dependencies] wasmtime = { version = "=50.0.1", default-features = false, features = [ "runtime", "cranelift", "wat", "std", "async", "component-model", "component-model-async", ] } tokio = { version = "1", features = ["rt", "macros"] } [profile.release] debug = 1
src/main.rs(withcomponent.watnext toCargo.toml):use std::time::Instant; use wasmtime::component::{Component, Linker, Val}; use wasmtime::{Config, Engine, Store}; const WAT: &str = include_str!("../component.wat"); fn kib(field: &str) -> u64 { let s = std::fs::read_to_string("/proc/self/status").unwrap(); let l = s.lines().find(|l| l.starts_with(field)).unwrap(); l.split_whitespace().nth(1).unwrap().parse().unwrap() } // Times one call and reports how far RSS peaked above the RSS right before it. macro_rules! bench { ($label:expr, $mib:expr, $call:expr) => {{ std::fs::write("/proc/self/clear_refs", "5").unwrap(); // reset VmHWM let base = kib("VmRSS:"); let t = Instant::now(); let r = $call; let dt = t.elapsed(); println!("{:<14} {:>3} MiB {:>10.1?} peak RSS +{:>5} MiB", $label, $mib, dt, kib("VmHWM:").saturating_sub(base) >> 10); r }}; } #[tokio::main(flavor = "current_thread")] async fn main() -> wasmtime::Result<()> { let concurrent = std::env::var_os("NO_CONCURRENCY").is_none(); let mut config = Config::new(); config.concurrency_support(concurrent).wasm_component_model_async(concurrent); let engine = Engine::new(&config)?; let component = Component::new(&engine, WAT)?; let mut store = Store::new(&engine, ()); // The default (128 MiB) rejects dynamic lifts of list<u8> above ~2.7 MiB, since // each element is charged size_of::<Val>() = 48 bytes. store.set_hostcall_fuel(usize::MAX); let instance = Linker::new(&engine).instantiate_async(&mut store, &component).await?; let echo = instance.get_func(&mut store, "echo").unwrap(); let len = instance.get_func(&mut store, "len").unwrap(); let echo_t = echo.typed::<(Vec<u8>,), (Vec<u8>,)>(&store)?; let len_t = len.typed::<(Vec<u8>,), (u32,)>(&store)?; println!("concurrency_support = {concurrent}, size_of::<Val>() = {}", size_of::<Val>()); for mib in [1usize, 16, 64] { let bytes = vec![7u8; mib << 20]; let params = [Val::List(bytes.iter().map(|b| Val::U8(*b)).collect())]; let mut out = [Val::Bool(false)]; bench!("dynamic len", mib, len.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(out[0], Val::U32(n) if n as usize == bytes.len())); bench!("dynamic echo", mib, echo.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(&out[0], Val::List(v) if v.len() == bytes.len())); drop((params, out)); let arg = (bytes.clone(),); let (n,) = bench!("typed len", mib, len_t.call_async(&mut store, arg).await?); assert_eq!(n as usize, bytes.len()); let arg = (bytes.clone(),); let (v,) = bench!("typed echo", mib, echo_t.call_async(&mut store, arg).await?); assert_eq!(v, bytes); } Ok(()) }Steps to Reproduce
- Create the project above (
Cargo.toml,src/main.rs,component.wat).- Run
cargo run --release(Linux: the peak-RSS column reads/proc/self/clear_refsandVmHWM).- Run
NO_CONCURRENCY=1 cargo run --releaseto compare withConfig::concurrency_support(false).- Remove the
store.set_hostcall_fuel(usize::MAX)line and run again to see the default hostcall fuel reject the dynamicechoat 3 MiB.Expected Results
A dynamic call moving a
list<u8>costs within a small factor of the typed call, as both copy the same bytes between host and guest: time and host memory proportional to the list's bytes, and the default hostcall fuel admitting the same list sizes on both paths.Actual Results
At 16-64 MiB the dynamic calls are 100-200x slower than the typed ones, and host memory rises by about 48 bytes per element (
size_of::<Val>() == 48): a 16 MiBlist<u8>is a 768 MiBVec<Val>.Concurrency support on (the default):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len(lower only)25-51 ms 390-523 ms 2.2-2.9 s +782 / +3119 MiB typed len0.15 ms 2.5-2.7 ms 6.2-12.4 ms ~0 / ~0 MiB dynamic echo(lower + lift)46-104 ms 722-837 ms 4.4-5.8 s +768 / +3084 MiB typed echo0.4-2.2 ms 5.7-7.8 ms 19-28 ms +16 / +63 MiB Concurrency support off (
NO_CONCURRENCY=1, same binary):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len11.6 ms 175-189 ms 752-767 ms +15 / +48 MiB dynamic echo33.4 ms 497-538 ms 2.4-2.5 s +768 / +3084 MiB typed len/echo0.12 / 0.33-0.40 ms 2.6-3.5 / 6.0-7.7 ms 8.1-8.5 / 24-26 ms ~0 / +16, +63 MiB
- With concurrency support on, the dynamic
len(lowering only) takes 2-4x as long as with it off, and its peak RSS rises by an extra 48 B per element: the arguments are deep-copied (params.to_vec(), see below).- With the default hostcall fuel (128 MiB), the dynamic
echofails at 3 MiB:too much data is being copied between the host and the guest: fuel allocated for hostcalls has been exhausted. The dynamic lift is chargedsize_of::<Val>()per element, the typed onesize_of::<u8>(), which stays within the default up to 128 MiB.Versions and Environment
Wasmtime version or commit: 50.0.1 (features
runtime,cranelift,wat,std,async,component-model,component-model-async)Operating system: Linux 7.3 (CachyOS); rustc 1.99.1, release build
Architecture: x86_64 (AMD Ryzen 7 5700X, 8C/16T, 32 GiB RAM)
Extra Info
Most of this reasoning was run by claude itself and I cross validated it's findings.
Context: Hit this in witgraph, a runtime that wires component exports into a graph at runtime, so it cannot name
TypedFunctypes; the same transfer through jco is about 100x faster than through the dynamic wasmtime path.Where the time goes (wasmtime 50.0.1,
crates/wasmtime/src/runtime/component/):
- The
Valrepresentation.Val::List(Vec<Val>)is defined atvalues.rs:81, andsize_of::<Val>()is 48.- Lifting. The list arm of
Val::load(values.rs:261-264) callsload_list(values.rs:1021-1048), which builds the result with(0..len).map(|index| Val::load(cx, elem, &cx.memory()[...])). That allocates oneVal::U8per byte (values.rs:247). The fuel check atvalues.rs:1031chargeslen * size_of::<Val>(). The typed path chargeslen * size_of::<T>()(func/typed.rs:1781), and its integer liftlinear_lift_into_from_memory(func/typed.rs:995-1007) extends from a little-endian slice in one pass.- Lowering. The list arms of
Val::lower(values.rs:469-475) andVal::store(values.rs:615-622) calllower_list(values.rs:1163-1182).lower_listcallsitem.store(cx, element_type, element_ptr)once per element (values.rs:1178). Each of those calls dispatches on(InterfaceType, Val)(values.rs:579) and then runsu8::linear_lower_to_memory, which writes*cx.get(offset) = self.to_le_bytes()(func/typed.rs:934).LowerContext::get(func/options.rs:231-243) callsas_slice_mut(func/options.rs:131-133) →Instance::options_memory_mut(instance.rs:498) →options_memory_raw(instance.rs:461-477). That chain looks up the instance, its canonical options and the runtime memory definition, then rebuilds and bounds-checks the slice, once per byte. The typed path does that once per list inlinear_store_list_to_memory(func/typed.rs:938-973).- The argument copy. With concurrency support on,
Func::call_async(func.rs:288-304) goes throughstart_call_concurrent(func.rs:298), as doesFunc::call_concurrent(concurrent/func.rs:113-122).do_start_call_concurrentthen deep-copies the arguments: `self.prepare_call_dynamic(store.as_context_mut(), params.
[message truncated]
sansmoraxz added the bug label to Issue #15105.
sansmoraxz edited issue #15105:
Test Case
component.wat: a component exportingecho: func(data: list<u8>) -> list<u8>, which hands the list back, andlen: func(data: list<u8>) -> u32, which only lowers it.;; `echo` hands the list back; `len` returns its length (isolates lowering). ;; `realloc` always returns offset 16 (one allocation per call), growing memory as needed. (component (core module $m (memory (export "memory") 1) (func (export "realloc") (param i32 i32 i32 i32) (result i32) (local $pages i32) (local.set $pages (i32.shr_u (i32.add (local.get 3) (i32.const 65551)) (i32.const 16))) (if (i32.gt_u (local.get $pages) (memory.size)) (then (drop (memory.grow (i32.sub (local.get $pages) (memory.size)))))) (i32.const 16)) (func (export "echo") (param i32 i32) (result i32) (i32.store (i32.const 0) (local.get 0)) (i32.store (i32.const 4) (local.get 1)) (i32.const 0)) (func (export "len") (param i32 i32) (result i32) (local.get 1))) (core instance $i (instantiate $m)) (func (export "echo") (param "data" (list u8)) (result (list u8)) (canon lift (core func $i "echo") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))) (func (export "len") (param "data" (list u8)) (result u32) (canon lift (core func $i "len") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))))The host program calls both exports with 1, 16 and 64 MiB lists, dynamically (
Func::call_asyncwithVal::List, as an embedder that only learns signatures at runtime must) and throughTypedFunc<(Vec<u8>,), _>, and prints each call's time and how far peak RSS rose during it.
Cargo.toml:[package] name = "wasmtime-val-list-repro" version = "0.1.0" edition = "2024" [dependencies] wasmtime = { version = "=50.0.1", default-features = false, features = [ "runtime", "cranelift", "wat", "std", "async", "component-model", "component-model-async", ] } tokio = { version = "1", features = ["rt", "macros"] } [profile.release] debug = 1
src/main.rs(withcomponent.watnext toCargo.toml):use std::time::Instant; use wasmtime::component::{Component, Linker, Val}; use wasmtime::{Config, Engine, Store}; const WAT: &str = include_str!("../component.wat"); fn kib(field: &str) -> u64 { let s = std::fs::read_to_string("/proc/self/status").unwrap(); let l = s.lines().find(|l| l.starts_with(field)).unwrap(); l.split_whitespace().nth(1).unwrap().parse().unwrap() } // Times one call and reports how far RSS peaked above the RSS right before it. macro_rules! bench { ($label:expr, $mib:expr, $call:expr) => {{ std::fs::write("/proc/self/clear_refs", "5").unwrap(); // reset VmHWM let base = kib("VmRSS:"); let t = Instant::now(); let r = $call; let dt = t.elapsed(); println!("{:<14} {:>3} MiB {:>10.1?} peak RSS +{:>5} MiB", $label, $mib, dt, kib("VmHWM:").saturating_sub(base) >> 10); r }}; } #[tokio::main(flavor = "current_thread")] async fn main() -> wasmtime::Result<()> { let concurrent = std::env::var_os("NO_CONCURRENCY").is_none(); let mut config = Config::new(); config.concurrency_support(concurrent).wasm_component_model_async(concurrent); let engine = Engine::new(&config)?; let component = Component::new(&engine, WAT)?; let mut store = Store::new(&engine, ()); // The default (128 MiB) rejects dynamic lifts of list<u8> above ~2.7 MiB, since // each element is charged size_of::<Val>() = 48 bytes. store.set_hostcall_fuel(usize::MAX); let instance = Linker::new(&engine).instantiate_async(&mut store, &component).await?; let echo = instance.get_func(&mut store, "echo").unwrap(); let len = instance.get_func(&mut store, "len").unwrap(); let echo_t = echo.typed::<(Vec<u8>,), (Vec<u8>,)>(&store)?; let len_t = len.typed::<(Vec<u8>,), (u32,)>(&store)?; println!("concurrency_support = {concurrent}, size_of::<Val>() = {}", size_of::<Val>()); for mib in [1usize, 16, 64] { let bytes = vec![7u8; mib << 20]; let params = [Val::List(bytes.iter().map(|b| Val::U8(*b)).collect())]; let mut out = [Val::Bool(false)]; bench!("dynamic len", mib, len.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(out[0], Val::U32(n) if n as usize == bytes.len())); bench!("dynamic echo", mib, echo.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(&out[0], Val::List(v) if v.len() == bytes.len())); drop((params, out)); let arg = (bytes.clone(),); let (n,) = bench!("typed len", mib, len_t.call_async(&mut store, arg).await?); assert_eq!(n as usize, bytes.len()); let arg = (bytes.clone(),); let (v,) = bench!("typed echo", mib, echo_t.call_async(&mut store, arg).await?); assert_eq!(v, bytes); } Ok(()) }Steps to Reproduce
- Create the project above (
Cargo.toml,src/main.rs,component.wat).- Run
cargo run --release(Linux: the peak-RSS column reads/proc/self/clear_refsandVmHWM).- Run
NO_CONCURRENCY=1 cargo run --releaseto compare withConfig::concurrency_support(false).- Remove the
store.set_hostcall_fuel(usize::MAX)line and run again to see the default hostcall fuel reject the dynamicechoat 3 MiB.Expected Results
A dynamic call moving a
list<u8>costs within a small factor of the typed call, as both copy the same bytes between host and guest: time and host memory proportional to the list's bytes, and the default hostcall fuel admitting the same list sizes on both paths.Actual Results
At 16-64 MiB the dynamic calls are 100-200x slower than the typed ones, and host memory rises by about 48 bytes per element (
size_of::<Val>() == 48): a 16 MiBlist<u8>is a 768 MiBVec<Val>.Concurrency support on (the default):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len(lower only)25-51 ms 390-523 ms 2.2-2.9 s +782 / +3119 MiB typed len0.15 ms 2.5-2.7 ms 6.2-12.4 ms ~0 / ~0 MiB dynamic echo(lower + lift)46-104 ms 722-837 ms 4.4-5.8 s +768 / +3084 MiB typed echo0.4-2.2 ms 5.7-7.8 ms 19-28 ms +16 / +63 MiB Concurrency support off (
NO_CONCURRENCY=1, same binary):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len11.6 ms 175-189 ms 752-767 ms +15 / +48 MiB dynamic echo33.4 ms 497-538 ms 2.4-2.5 s +768 / +3084 MiB typed len/echo0.12 / 0.33-0.40 ms 2.6-3.5 / 6.0-7.7 ms 8.1-8.5 / 24-26 ms ~0 / +16, +63 MiB
- With concurrency support on, the dynamic
len(lowering only) takes 2-4x as long as with it off, and its peak RSS rises by an extra 48 B per element: the arguments are deep-copied (params.to_vec(), see below).- With the default hostcall fuel (128 MiB), the dynamic
echofails at 3 MiB:too much data is being copied between the host and the guest: fuel allocated for hostcalls has been exhausted. The dynamic lift is chargedsize_of::<Val>()per element, the typed onesize_of::<u8>(), which stays within the default up to 128 MiB.Versions and Environment
Wasmtime version or commit: 50.0.1 (features
runtime,cranelift,wat,std,async,component-model,component-model-async)Operating system: Linux 7.3 (CachyOS); rustc 1.99.1, release build
Architecture: x86_64 (AMD Ryzen 7 5700X, 8C/16T, 32 GiB RAM)
Extra Info
Most of this reasoning was run by claude itself and I cross validated it's findings.
Context: Hit this in witgraph, a runtime that wires component exports into a graph at runtime, so it cannot name
TypedFunctypes; the same transfer through jco is about 100x faster than through the dynamic wasmtime path.Where the time goes (wasmtime 50.0.1,
crates/wasmtime/src/runtime/component/):
- The
Valrepresentation.Val::List(Vec<Val>)is defined atvalues.rs:81, andsize_of::<Val>()is 48.- Lifting. The list arm of
Val::load(values.rs:261-264) callsload_list(values.rs:1021-1048), which builds the result with(0..len).map(|index| Val::load(cx, elem, &cx.memory()[...])). That allocates oneVal::U8per byte (values.rs:247). The fuel check atvalues.rs:1031chargeslen * size_of::<Val>(). The typed path chargeslen * size_of::<T>()(func/typed.rs:1781), and its integer liftlinear_lift_into_from_memory(func/typed.rs:995-1007) extends from a little-endian slice in one pass.- Lowering. The list arms of
Val::lower(values.rs:469-475) andVal::store(values.rs:615-622) calllower_list(values.rs:1163-1182).lower_listcallsitem.store(cx, element_type, element_ptr)once per element (values.rs:1178). Each of those calls dispatches on(InterfaceType, Val)(values.rs:579) and then runsu8::linear_lower_to_memory, which writes*cx.get(offset) = self.to_le_bytes()(func/typed.rs:934).LowerContext::get(func/options.rs:231-243) callsas_slice_mut(func/options.rs:131-133) →Instance::options_memory_mut(instance.rs:498) →options_memory_raw(instance.rs:461-477). That chain looks up the instance, its canonical options and the runtime memory definition, then rebuilds and bounds-checks the slice, once per byte. The typed path does that once per list inlinear_store_list_to_memory(func/typed.rs:938-973).- The argument copy. With concurrency support on,
Func::call_async(func.rs:288-304) goes throughstart_call_concurrent(func.rs:298), as doesFunc::call_concurrent(concurrent/func.rs:113-122).do_start_call_concurrentthen deep-copies the arguments: `self.prepare_call_dynamic(store.as_context_mut(), params.
[message truncated]
alexcrichton commented on issue #15105:
@sansmoraxz can you confirm you're following our AI tool usage policy? This is just a massive dump from an LLM.
The documentation of
Valexplicitly saysNote that this is not an efficient representation
Are you unable to use typed APIs? If so, can you offer some discussion as to why and perhaps what you're hoping to achieve with this issue? (ideally without an LLM in the middle)
sansmoraxz edited issue #15105:
Test Case
component.wat: a component exportingecho: func(data: list<u8>) -> list<u8>, which hands the list back, andlen: func(data: list<u8>) -> u32, which only lowers it.;; `echo` hands the list back; `len` returns its length (isolates lowering). ;; `realloc` always returns offset 16 (one allocation per call), growing memory as needed. (component (core module $m (memory (export "memory") 1) (func (export "realloc") (param i32 i32 i32 i32) (result i32) (local $pages i32) (local.set $pages (i32.shr_u (i32.add (local.get 3) (i32.const 65551)) (i32.const 16))) (if (i32.gt_u (local.get $pages) (memory.size)) (then (drop (memory.grow (i32.sub (local.get $pages) (memory.size)))))) (i32.const 16)) (func (export "echo") (param i32 i32) (result i32) (i32.store (i32.const 0) (local.get 0)) (i32.store (i32.const 4) (local.get 1)) (i32.const 0)) (func (export "len") (param i32 i32) (result i32) (local.get 1))) (core instance $i (instantiate $m)) (func (export "echo") (param "data" (list u8)) (result (list u8)) (canon lift (core func $i "echo") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))) (func (export "len") (param "data" (list u8)) (result u32) (canon lift (core func $i "len") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))))The host program calls both exports with 1, 16 and 64 MiB lists, dynamically (
Func::call_asyncwithVal::List, as an embedder that only learns signatures at runtime must) and throughTypedFunc<(Vec<u8>,), _>, and prints each call's time and how far peak RSS rose during it.
Cargo.toml:[package] name = "wasmtime-val-list-repro" version = "0.1.0" edition = "2024" [dependencies] wasmtime = { version = "=50.0.1", default-features = false, features = [ "runtime", "cranelift", "wat", "std", "async", "component-model", "component-model-async", ] } tokio = { version = "1", features = ["rt", "macros"] } [profile.release] debug = 1
src/main.rs(withcomponent.watnext toCargo.toml):use std::time::Instant; use wasmtime::component::{Component, Linker, Val}; use wasmtime::{Config, Engine, Store}; const WAT: &str = include_str!("../component.wat"); fn kib(field: &str) -> u64 { let s = std::fs::read_to_string("/proc/self/status").unwrap(); let l = s.lines().find(|l| l.starts_with(field)).unwrap(); l.split_whitespace().nth(1).unwrap().parse().unwrap() } // Times one call and reports how far RSS peaked above the RSS right before it. macro_rules! bench { ($label:expr, $mib:expr, $call:expr) => {{ std::fs::write("/proc/self/clear_refs", "5").unwrap(); // reset VmHWM let base = kib("VmRSS:"); let t = Instant::now(); let r = $call; let dt = t.elapsed(); println!("{:<14} {:>3} MiB {:>10.1?} peak RSS +{:>5} MiB", $label, $mib, dt, kib("VmHWM:").saturating_sub(base) >> 10); r }}; } #[tokio::main(flavor = "current_thread")] async fn main() -> wasmtime::Result<()> { let concurrent = std::env::var_os("NO_CONCURRENCY").is_none(); let mut config = Config::new(); config.concurrency_support(concurrent).wasm_component_model_async(concurrent); let engine = Engine::new(&config)?; let component = Component::new(&engine, WAT)?; let mut store = Store::new(&engine, ()); // The default (128 MiB) rejects dynamic lifts of list<u8> above ~2.7 MiB, since // each element is charged size_of::<Val>() = 48 bytes. store.set_hostcall_fuel(usize::MAX); let instance = Linker::new(&engine).instantiate_async(&mut store, &component).await?; let echo = instance.get_func(&mut store, "echo").unwrap(); let len = instance.get_func(&mut store, "len").unwrap(); let echo_t = echo.typed::<(Vec<u8>,), (Vec<u8>,)>(&store)?; let len_t = len.typed::<(Vec<u8>,), (u32,)>(&store)?; println!("concurrency_support = {concurrent}, size_of::<Val>() = {}", size_of::<Val>()); for mib in [1usize, 16, 64] { let bytes = vec![7u8; mib << 20]; let params = [Val::List(bytes.iter().map(|b| Val::U8(*b)).collect())]; let mut out = [Val::Bool(false)]; bench!("dynamic len", mib, len.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(out[0], Val::U32(n) if n as usize == bytes.len())); bench!("dynamic echo", mib, echo.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(&out[0], Val::List(v) if v.len() == bytes.len())); drop((params, out)); let arg = (bytes.clone(),); let (n,) = bench!("typed len", mib, len_t.call_async(&mut store, arg).await?); assert_eq!(n as usize, bytes.len()); let arg = (bytes.clone(),); let (v,) = bench!("typed echo", mib, echo_t.call_async(&mut store, arg).await?); assert_eq!(v, bytes); } Ok(()) }Steps to Reproduce
- Create the project above (
Cargo.toml,src/main.rs,component.wat).- Run
cargo run --release(Linux: the peak-RSS column reads/proc/self/clear_refsandVmHWM).- Run
NO_CONCURRENCY=1 cargo run --releaseto compare withConfig::concurrency_support(false).- Remove the
store.set_hostcall_fuel(usize::MAX)line and run again to see the default hostcall fuel reject the dynamicechoat 3 MiB.Expected Results
A dynamic call moving a
list<u8>costs within a small factor of the typed call, as both copy the same bytes between host and guest: time and host memory proportional to the list's bytes, and the default hostcall fuel admitting the same list sizes on both paths.Actual Results
At 16-64 MiB the dynamic calls are 100-200x slower than the typed ones, and host memory rises by about 48 bytes per element (
size_of::<Val>() == 48): a 16 MiBlist<u8>is a 768 MiBVec<Val>.Concurrency support on (the default):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len(lower only)25-51 ms 390-523 ms 2.2-2.9 s +782 / +3119 MiB typed len0.15 ms 2.5-2.7 ms 6.2-12.4 ms ~0 / ~0 MiB dynamic echo(lower + lift)46-104 ms 722-837 ms 4.4-5.8 s +768 / +3084 MiB typed echo0.4-2.2 ms 5.7-7.8 ms 19-28 ms +16 / +63 MiB Concurrency support off (
NO_CONCURRENCY=1, same binary):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len11.6 ms 175-189 ms 752-767 ms +15 / +48 MiB dynamic echo33.4 ms 497-538 ms 2.4-2.5 s +768 / +3084 MiB typed len/echo0.12 / 0.33-0.40 ms 2.6-3.5 / 6.0-7.7 ms 8.1-8.5 / 24-26 ms ~0 / +16, +63 MiB
- With concurrency support on, the dynamic
len(lowering only) takes 2-4x as long as with it off, and its peak RSS rises by an extra 48 B per element: the arguments are deep-copied (params.to_vec(), see below).- With the default hostcall fuel (128 MiB), the dynamic
echofails at 3 MiB:too much data is being copied between the host and the guest: fuel allocated for hostcalls has been exhausted. The dynamic lift is chargedsize_of::<Val>()per element, the typed onesize_of::<u8>(), which stays within the default up to 128 MiB.Versions and Environment
Wasmtime version or commit: 50.0.1 (features
runtime,cranelift,wat,std,async,component-model,component-model-async)Operating system: Linux 7.3 (CachyOS); rustc 1.99.1, release build
Architecture: x86_64 (AMD Ryzen 7 5700X, 8C/16T, 32 GiB RAM)
Extra Info
Most of this reasoning was run by claude itself and I cross validated it's findings.
Context: Hit this in witgraph, a runtime that wires component exports into a graph at runtime, so it cannot name
TypedFunctypes; the same transfer through jco is about 100x faster than through the dynamic wasmtime path.Spoiler: word dump from llms
<details>Where the time goes (wasmtime 50.0.1,
crates/wasmtime/src/runtime/component/):
- The
Valrepresentation.Val::List(Vec<Val>)is defined atvalues.rs:81, andsize_of::<Val>()is 48.- Lifting. The list arm of
Val::load(values.rs:261-264) callsload_list(values.rs:1021-1048), which builds the result with(0..len).map(|index| Val::load(cx, elem, &cx.memory()[...])). That allocates oneVal::U8per byte (values.rs:247). The fuel check atvalues.rs:1031chargeslen * size_of::<Val>(). The typed path chargeslen * size_of::<T>()(func/typed.rs:1781), and its integer liftlinear_lift_into_from_memory(func/typed.rs:995-1007) extends from a little-endian slice in one pass.- Lowering. The list arms of
Val::lower(values.rs:469-475) andVal::store(values.rs:615-622) calllower_list(values.rs:1163-1182).lower_listcallsitem.store(cx, element_type, element_ptr)once per element (values.rs:1178). Each of those calls dispatches on(InterfaceType, Val)(values.rs:579) and then runsu8::linear_lower_to_memory, which writes*cx.get(offset) = self.to_le_bytes()(func/typed.rs:934).LowerContext::get(func/options.rs:231-243) callsas_slice_mut(func/options.rs:131-133) →Instance::options_memory_mut(instance.rs:498) →options_memory_raw(instance.rs:461-477). That chain looks up the instance, its canonical options and the runtime memory definition, then rebuilds and bounds-checks the slice, once per byte. The typed path does that once per list inlinear_store_list_to_memory(func/typed.rs:938-973).- The argument copy. With concurrency support on,
Func::call_async(func.rs:288-304) goes throughstart_call_concurrent(func.rs:298), as doesFunc::call_concurrent(concurrent/func.rs:113-122).do_start_call_concurrentthen deep-copies the arguments: `self.prepare_cal
[message truncated]
sansmoraxz commented on issue #15105:
This is just a massive dump from an LLM.
Ahh, hidden under details now. You may just reproduce with the uploaded tar archive, if you don't want to deal with the word salad.
Are you unable to use typed APIs? If so, can you offer some discussion as to why and perhaps what you're hoping to achieve with this issue? (ideally without an LLM in the middle)
I believe I already linked the repo I was facing this problem on. Typed API would likely be possible but then I would have to rearchitect the entire thing (which given current LLMs and it remaining unpublished maybe not that big of a thing). My application leverages the component model. Each node supplied as component and each node declares it's inputs and outputs in their WIT contracts (More details in the repo READMEs / docs). The host becomes aware of each node's contract only when it loads the component, by lowering the WIT of its
runexport into ports. Each graph can run anywhere, or at least that's the aim (that supports wasmtime or via jco with the web adapter) given the additional capabilities declared to be needed are provided by the host.Was trying to tune performance of this entire orcastation and while benchmarking one of the surprising things I observed was that it ran slower on wasmtime compared to jco. Went down the rabit hole and encountered this.
<details>
Word dump from LLMs
We tried several ways around this. These are the times per hop for a 16 MiB
list<u8>:
Approach Time per hop Drawback Valtoday~715 ms The cost is building and walking one Val::U8per element, both lifting and lowering.A type-erased TypedFunc~3.8 ms Built on __internalAPIs, so we can't ship it.Generated adapter components ~20 ms Also turned up a separate table leak with canon lower async(we'll file that on its own).Bindings generated ahead of time ~6 ms Only works for components known when the host is built, which defeats the point. Patched Valwith a packed list variant~3–8 ms This is the shape of fix we're asking for. For large data on devices (tensors, GPU buffers), we've since moved to passing resource handles between nodes. That costs about 10 µs per hop and doesn't depend on this issue. But ordinary value ports still carry things like
list<u8>, frame records andlist<f32>. Those are exactly where the dynamic path costs about 100× more than the typed one.</details>
sansmoraxz edited a comment on issue #15105:
This is just a massive dump from an LLM.
Ahh, hidden under details now. You may just reproduce with the uploaded tar archive, if you don't want to deal with the word salad.
Are you unable to use typed APIs? If so, can you offer some discussion as to why and perhaps what you're hoping to achieve with this issue? (ideally without an LLM in the middle)
I believe I already linked the repo I was facing this problem on. Typed API would likely be possible but then I would have to rearchitect the entire thing (which given current LLMs and it remaining unpublished maybe not that big of a thing). My application leverages the component model. Each node supplied as component and each node declares it's inputs and outputs in their WIT contracts (More details in the repo READMEs / docs). The host becomes aware of each node's contract only when it loads the component, by lowering the WIT of its
runexport into ports. Each graph can run anywhere, or at least that's the aim (that supports wasmtime or via jco with the web adapter) given the additional capabilities declared to be needed are provided by the host.Was trying to tune performance of this entire orcastation and while benchmarking one of the surprising things I observed was that it ran slower on wasmtime compared to jco. Went down the rabit hole and encountered this.
<details>
Word dump from LLMs
We tried several ways around this. These are the times per hop for a 16 MiB
list<u8>:
Approach Time per hop Drawback Valtoday~715 ms The cost is building and walking one Val::U8per element, both lifting and lowering.A type-erased TypedFunc~3.8 ms Built on __internalAPIs, so we can't ship it.Generated adapter components ~20 ms Also turned up a separate table leak with canon lower async(we'll file that on its own).Bindings generated ahead of time ~6 ms Only works for components known when the host is built, which defeats the point. Patched Valwith a packed list variant~3–8 ms This is the shape of fix we're asking for. For large data on devices (tensors, GPU buffers), we've since moved to passing resource handles between nodes (https://github.com/sansmoraxz/witgraph/pull/22). That costs about 10 µs per hop and doesn't depend on this issue. But ordinary value ports still carry things like
list<u8>, frame records andlist<f32>. Those are exactly where the dynamic path costs about 100× more than the typed one.</details>
sansmoraxz edited issue #15105:
Test Case
component.wat: a component exportingecho: func(data: list<u8>) -> list<u8>, which hands the list back, andlen: func(data: list<u8>) -> u32, which only lowers it.Sample repo below (also part of the attached artifacts):
<details>
;; `echo` hands the list back; `len` returns its length (isolates lowering). ;; `realloc` always returns offset 16 (one allocation per call), growing memory as needed. (component (core module $m (memory (export "memory") 1) (func (export "realloc") (param i32 i32 i32 i32) (result i32) (local $pages i32) (local.set $pages (i32.shr_u (i32.add (local.get 3) (i32.const 65551)) (i32.const 16))) (if (i32.gt_u (local.get $pages) (memory.size)) (then (drop (memory.grow (i32.sub (local.get $pages) (memory.size)))))) (i32.const 16)) (func (export "echo") (param i32 i32) (result i32) (i32.store (i32.const 0) (local.get 0)) (i32.store (i32.const 4) (local.get 1)) (i32.const 0)) (func (export "len") (param i32 i32) (result i32) (local.get 1))) (core instance $i (instantiate $m)) (func (export "echo") (param "data" (list u8)) (result (list u8)) (canon lift (core func $i "echo") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))) (func (export "len") (param "data" (list u8)) (result u32) (canon lift (core func $i "len") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))))The host program calls both exports with 1, 16 and 64 MiB lists, dynamically (
Func::call_asyncwithVal::List, as an embedder that only learns signatures at runtime must) and throughTypedFunc<(Vec<u8>,), _>, and prints each call's time and how far peak RSS rose during it.
Cargo.toml:[package] name = "wasmtime-val-list-repro" version = "0.1.0" edition = "2024" [dependencies] wasmtime = { version = "=50.0.1", default-features = false, features = [ "runtime", "cranelift", "wat", "std", "async", "component-model", "component-model-async", ] } tokio = { version = "1", features = ["rt", "macros"] } [profile.release] debug = 1
src/main.rs(withcomponent.watnext toCargo.toml):use std::time::Instant; use wasmtime::component::{Component, Linker, Val}; use wasmtime::{Config, Engine, Store}; const WAT: &str = include_str!("../component.wat"); fn kib(field: &str) -> u64 { let s = std::fs::read_to_string("/proc/self/status").unwrap(); let l = s.lines().find(|l| l.starts_with(field)).unwrap(); l.split_whitespace().nth(1).unwrap().parse().unwrap() } // Times one call and reports how far RSS peaked above the RSS right before it. macro_rules! bench { ($label:expr, $mib:expr, $call:expr) => {{ std::fs::write("/proc/self/clear_refs", "5").unwrap(); // reset VmHWM let base = kib("VmRSS:"); let t = Instant::now(); let r = $call; let dt = t.elapsed(); println!("{:<14} {:>3} MiB {:>10.1?} peak RSS +{:>5} MiB", $label, $mib, dt, kib("VmHWM:").saturating_sub(base) >> 10); r }}; } #[tokio::main(flavor = "current_thread")] async fn main() -> wasmtime::Result<()> { let concurrent = std::env::var_os("NO_CONCURRENCY").is_none(); let mut config = Config::new(); config.concurrency_support(concurrent).wasm_component_model_async(concurrent); let engine = Engine::new(&config)?; let component = Component::new(&engine, WAT)?; let mut store = Store::new(&engine, ()); // The default (128 MiB) rejects dynamic lifts of list<u8> above ~2.7 MiB, since // each element is charged size_of::<Val>() = 48 bytes. store.set_hostcall_fuel(usize::MAX); let instance = Linker::new(&engine).instantiate_async(&mut store, &component).await?; let echo = instance.get_func(&mut store, "echo").unwrap(); let len = instance.get_func(&mut store, "len").unwrap(); let echo_t = echo.typed::<(Vec<u8>,), (Vec<u8>,)>(&store)?; let len_t = len.typed::<(Vec<u8>,), (u32,)>(&store)?; println!("concurrency_support = {concurrent}, size_of::<Val>() = {}", size_of::<Val>()); for mib in [1usize, 16, 64] { let bytes = vec![7u8; mib << 20]; let params = [Val::List(bytes.iter().map(|b| Val::U8(*b)).collect())]; let mut out = [Val::Bool(false)]; bench!("dynamic len", mib, len.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(out[0], Val::U32(n) if n as usize == bytes.len())); bench!("dynamic echo", mib, echo.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(&out[0], Val::List(v) if v.len() == bytes.len())); drop((params, out)); let arg = (bytes.clone(),); let (n,) = bench!("typed len", mib, len_t.call_async(&mut store, arg).await?); assert_eq!(n as usize, bytes.len()); let arg = (bytes.clone(),); let (v,) = bench!("typed echo", mib, echo_t.call_async(&mut store, arg).await?); assert_eq!(v, bytes); } Ok(()) }Steps to Reproduce
- Create the project above (
Cargo.toml,src/main.rs,component.wat).- Run
cargo run --release(Linux: the peak-RSS column reads/proc/self/clear_refsandVmHWM).- Run
NO_CONCURRENCY=1 cargo run --releaseto compare withConfig::concurrency_support(false).- Remove the
store.set_hostcall_fuel(usize::MAX)line and run again to see the default hostcall fuel reject the dynamicechoat 3 MiB.</details>
Expected Results
A dynamic call moving a
list<u8>costs within a small factor of the typed call, as both copy the same bytes between host and guest: time and host memory proportional to the list's bytes, and the default hostcall fuel admitting the same list sizes on both paths.Actual Results
At 16-64 MiB the dynamic calls are 100-200x slower than the typed ones, and host memory rises by about 48 bytes per element (
size_of::<Val>() == 48): a 16 MiBlist<u8>is a 768 MiBVec<Val>.Concurrency support on (the default):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len(lower only)25-51 ms 390-523 ms 2.2-2.9 s +782 / +3119 MiB typed len0.15 ms 2.5-2.7 ms 6.2-12.4 ms ~0 / ~0 MiB dynamic echo(lower + lift)46-104 ms 722-837 ms 4.4-5.8 s +768 / +3084 MiB typed echo0.4-2.2 ms 5.7-7.8 ms 19-28 ms +16 / +63 MiB Concurrency support off (
NO_CONCURRENCY=1, same binary):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len11.6 ms 175-189 ms 752-767 ms +15 / +48 MiB dynamic echo33.4 ms 497-538 ms 2.4-2.5 s +768 / +3084 MiB typed len/echo0.12 / 0.33-0.40 ms 2.6-3.5 / 6.0-7.7 ms 8.1-8.5 / 24-26 ms ~0 / +16, +63 MiB
- With concurrency support on, the dynamic
len(lowering only) takes 2-4x as long as with it off, and its peak RSS rises by an extra 48 B per element: the arguments are deep-copied (params.to_vec(), see below).- With the default hostcall fuel (128 MiB), the dynamic
echofails at 3 MiB:too much data is being copied between the host and the guest: fuel allocated for hostcalls has been exhausted. The dynamic lift is chargedsize_of::<Val>()per element, the typed onesize_of::<u8>(), which stays within the default up to 128 MiB.Versions and Environment
Wasmtime version or commit: 50.0.1 (features
runtime,cranelift,wat,std,async,component-model,component-model-async)Operating system: Linux 7.3 (CachyOS); rustc 1.99.1, release build
Architecture: x86_64 (AMD Ryzen 7 5700X, 8C/16T, 32 GiB RAM)
Extra Info
Most of this reasoning was run by claude itself and I cross validated it's findings.
Context: Hit this in witgraph, a runtime that wires component exports into a graph at runtime, so it cannot name
TypedFunctypes; the same transfer through jco is about 100x faster than through the dynamic wasmtime path.Spoiler: word dump from llms
<details>Where the time goes (wasmtime 50.0.1,
crates/wasmtime/src/runtime/component/):
- The
Valrepresentation.Val::List(Vec<Val>)is defined atvalues.rs:81, andsize_of::<Val>()is 48.- Lifting. The list arm of
Val::load(values.rs:261-264) callsload_list(values.rs:1021-1048), which builds the result with(0..len).map(|index| Val::load(cx, elem, &cx.memory()[...])). That allocates oneVal::U8per byte (values.rs:247). The fuel check atvalues.rs:1031chargeslen * size_of::<Val>(). The typed path chargeslen * size_of::<T>()(func/typed.rs:1781), and its integer liftlinear_lift_into_from_memory(func/typed.rs:995-1007) extends from a little-endian slice in one pass.- Lowering. The list arms of
Val::lower(values.rs:469-475) andVal::store(values.rs:615-622) calllower_list(values.rs:1163-1182).lower_listcallsitem.store(cx, element_type, element_ptr)once per element (values.rs:1178). Each of those calls dispatches on(InterfaceType, Val)(values.rs:579) and then runsu8::linear_lower_to_memory, which writes*cx.get(offset) = self.to_le_bytes()(func/typed.rs:934).LowerContext::get(func/options.rs:231-243) callsas_slice_mut(func/options.rs:131-133) →Instance::options_memory_mut(instance.rs:498) →options_memory_raw(instance.rs:461-477). That chain looks up the instance, its canonical options and the runtime memory definition, then rebuilds and bounds-checks the slice, once per byte. The typed path does that once per list inlinear_store_list_to_memory(func/typed.rs:938-973).- The argument copy. With concurrency support on,
Func::call_async(func.rs:288-304) goes throughstart_call_concurrent(func.rs:298), as doesFunc::call_concurrent(`concurrent/func.rs:113-1
[message truncated]
alexcrichton closed issue #15105:
Test Case
component.wat: a component exportingecho: func(data: list<u8>) -> list<u8>, which hands the list back, andlen: func(data: list<u8>) -> u32, which only lowers it.Sample repo below (also part of the attached artifacts):
<details>
;; `echo` hands the list back; `len` returns its length (isolates lowering). ;; `realloc` always returns offset 16 (one allocation per call), growing memory as needed. (component (core module $m (memory (export "memory") 1) (func (export "realloc") (param i32 i32 i32 i32) (result i32) (local $pages i32) (local.set $pages (i32.shr_u (i32.add (local.get 3) (i32.const 65551)) (i32.const 16))) (if (i32.gt_u (local.get $pages) (memory.size)) (then (drop (memory.grow (i32.sub (local.get $pages) (memory.size)))))) (i32.const 16)) (func (export "echo") (param i32 i32) (result i32) (i32.store (i32.const 0) (local.get 0)) (i32.store (i32.const 4) (local.get 1)) (i32.const 0)) (func (export "len") (param i32 i32) (result i32) (local.get 1))) (core instance $i (instantiate $m)) (func (export "echo") (param "data" (list u8)) (result (list u8)) (canon lift (core func $i "echo") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))) (func (export "len") (param "data" (list u8)) (result u32) (canon lift (core func $i "len") (memory (core memory $i "memory")) (realloc (core func $i "realloc")))))The host program calls both exports with 1, 16 and 64 MiB lists, dynamically (
Func::call_asyncwithVal::List, as an embedder that only learns signatures at runtime must) and throughTypedFunc<(Vec<u8>,), _>, and prints each call's time and how far peak RSS rose during it.
Cargo.toml:[package] name = "wasmtime-val-list-repro" version = "0.1.0" edition = "2024" [dependencies] wasmtime = { version = "=50.0.1", default-features = false, features = [ "runtime", "cranelift", "wat", "std", "async", "component-model", "component-model-async", ] } tokio = { version = "1", features = ["rt", "macros"] } [profile.release] debug = 1
src/main.rs(withcomponent.watnext toCargo.toml):use std::time::Instant; use wasmtime::component::{Component, Linker, Val}; use wasmtime::{Config, Engine, Store}; const WAT: &str = include_str!("../component.wat"); fn kib(field: &str) -> u64 { let s = std::fs::read_to_string("/proc/self/status").unwrap(); let l = s.lines().find(|l| l.starts_with(field)).unwrap(); l.split_whitespace().nth(1).unwrap().parse().unwrap() } // Times one call and reports how far RSS peaked above the RSS right before it. macro_rules! bench { ($label:expr, $mib:expr, $call:expr) => {{ std::fs::write("/proc/self/clear_refs", "5").unwrap(); // reset VmHWM let base = kib("VmRSS:"); let t = Instant::now(); let r = $call; let dt = t.elapsed(); println!("{:<14} {:>3} MiB {:>10.1?} peak RSS +{:>5} MiB", $label, $mib, dt, kib("VmHWM:").saturating_sub(base) >> 10); r }}; } #[tokio::main(flavor = "current_thread")] async fn main() -> wasmtime::Result<()> { let concurrent = std::env::var_os("NO_CONCURRENCY").is_none(); let mut config = Config::new(); config.concurrency_support(concurrent).wasm_component_model_async(concurrent); let engine = Engine::new(&config)?; let component = Component::new(&engine, WAT)?; let mut store = Store::new(&engine, ()); // The default (128 MiB) rejects dynamic lifts of list<u8> above ~2.7 MiB, since // each element is charged size_of::<Val>() = 48 bytes. store.set_hostcall_fuel(usize::MAX); let instance = Linker::new(&engine).instantiate_async(&mut store, &component).await?; let echo = instance.get_func(&mut store, "echo").unwrap(); let len = instance.get_func(&mut store, "len").unwrap(); let echo_t = echo.typed::<(Vec<u8>,), (Vec<u8>,)>(&store)?; let len_t = len.typed::<(Vec<u8>,), (u32,)>(&store)?; println!("concurrency_support = {concurrent}, size_of::<Val>() = {}", size_of::<Val>()); for mib in [1usize, 16, 64] { let bytes = vec![7u8; mib << 20]; let params = [Val::List(bytes.iter().map(|b| Val::U8(*b)).collect())]; let mut out = [Val::Bool(false)]; bench!("dynamic len", mib, len.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(out[0], Val::U32(n) if n as usize == bytes.len())); bench!("dynamic echo", mib, echo.call_async(&mut store, ¶ms, &mut out).await?); assert!(matches!(&out[0], Val::List(v) if v.len() == bytes.len())); drop((params, out)); let arg = (bytes.clone(),); let (n,) = bench!("typed len", mib, len_t.call_async(&mut store, arg).await?); assert_eq!(n as usize, bytes.len()); let arg = (bytes.clone(),); let (v,) = bench!("typed echo", mib, echo_t.call_async(&mut store, arg).await?); assert_eq!(v, bytes); } Ok(()) }Steps to Reproduce
- Create the project above (
Cargo.toml,src/main.rs,component.wat).- Run
cargo run --release(Linux: the peak-RSS column reads/proc/self/clear_refsandVmHWM).- Run
NO_CONCURRENCY=1 cargo run --releaseto compare withConfig::concurrency_support(false).- Remove the
store.set_hostcall_fuel(usize::MAX)line and run again to see the default hostcall fuel reject the dynamicechoat 3 MiB.</details>
Expected Results
A dynamic call moving a
list<u8>costs within a small factor of the typed call, as both copy the same bytes between host and guest: time and host memory proportional to the list's bytes, and the default hostcall fuel admitting the same list sizes on both paths.Actual Results
At 16-64 MiB the dynamic calls are 100-200x slower than the typed ones, and host memory rises by about 48 bytes per element (
size_of::<Val>() == 48): a 16 MiBlist<u8>is a 768 MiBVec<Val>.Concurrency support on (the default):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len(lower only)25-51 ms 390-523 ms 2.2-2.9 s +782 / +3119 MiB typed len0.15 ms 2.5-2.7 ms 6.2-12.4 ms ~0 / ~0 MiB dynamic echo(lower + lift)46-104 ms 722-837 ms 4.4-5.8 s +768 / +3084 MiB typed echo0.4-2.2 ms 5.7-7.8 ms 19-28 ms +16 / +63 MiB Concurrency support off (
NO_CONCURRENCY=1, same binary):
call 1 MiB 16 MiB 64 MiB peak RSS rise at 16 / 64 MiB dynamic len11.6 ms 175-189 ms 752-767 ms +15 / +48 MiB dynamic echo33.4 ms 497-538 ms 2.4-2.5 s +768 / +3084 MiB typed len/echo0.12 / 0.33-0.40 ms 2.6-3.5 / 6.0-7.7 ms 8.1-8.5 / 24-26 ms ~0 / +16, +63 MiB
- With concurrency support on, the dynamic
len(lowering only) takes 2-4x as long as with it off, and its peak RSS rises by an extra 48 B per element: the arguments are deep-copied (params.to_vec(), see below).- With the default hostcall fuel (128 MiB), the dynamic
echofails at 3 MiB:too much data is being copied between the host and the guest: fuel allocated for hostcalls has been exhausted. The dynamic lift is chargedsize_of::<Val>()per element, the typed onesize_of::<u8>(), which stays within the default up to 128 MiB.Versions and Environment
Wasmtime version or commit: 50.0.1 (features
runtime,cranelift,wat,std,async,component-model,component-model-async)Operating system: Linux 7.3 (CachyOS); rustc 1.99.1, release build
Architecture: x86_64 (AMD Ryzen 7 5700X, 8C/16T, 32 GiB RAM)
Extra Info
Most of this reasoning was run by claude itself and I cross validated it's findings.
Context: Hit this in witgraph, a runtime that wires component exports into a graph at runtime, so it cannot name
TypedFunctypes; the same transfer through jco is about 100x faster than through the dynamic wasmtime path.Spoiler: word dump from llms
<details>Where the time goes (wasmtime 50.0.1,
crates/wasmtime/src/runtime/component/):
- The
Valrepresentation.Val::List(Vec<Val>)is defined atvalues.rs:81, andsize_of::<Val>()is 48.- Lifting. The list arm of
Val::load(values.rs:261-264) callsload_list(values.rs:1021-1048), which builds the result with(0..len).map(|index| Val::load(cx, elem, &cx.memory()[...])). That allocates oneVal::U8per byte (values.rs:247). The fuel check atvalues.rs:1031chargeslen * size_of::<Val>(). The typed path chargeslen * size_of::<T>()(func/typed.rs:1781), and its integer liftlinear_lift_into_from_memory(func/typed.rs:995-1007) extends from a little-endian slice in one pass.- Lowering. The list arms of
Val::lower(values.rs:469-475) andVal::store(values.rs:615-622) calllower_list(values.rs:1163-1182).lower_listcallsitem.store(cx, element_type, element_ptr)once per element (values.rs:1178). Each of those calls dispatches on(InterfaceType, Val)(values.rs:579) and then runsu8::linear_lower_to_memory, which writes*cx.get(offset) = self.to_le_bytes()(func/typed.rs:934).LowerContext::get(func/options.rs:231-243) callsas_slice_mut(func/options.rs:131-133) →Instance::options_memory_mut(instance.rs:498) →options_memory_raw(instance.rs:461-477). That chain looks up the instance, its canonical options and the runtime memory definition, then rebuilds and bounds-checks the slice, once per byte. The typed path does that once per list inlinear_store_list_to_memory(func/typed.rs:938-973).- The argument copy. With concurrency support on,
Func::call_async(func.rs:288-304) goes throughstart_call_concurrent(func.rs:298), as doesFunc::call_concurrent(`concurrent/func.rs:113
[message truncated]
alexcrichton commented on issue #15105:
I'd recommend using either typed APIs for exchange through the host or component composition if you don't need data to go through the host and it's component-to-component. If that doesn't work for you, though, feel free to post here and I can reopen.
sansmoraxz commented on issue #15105:
if you don't need data to go through the host
My current model is for most values outputs from one node are lifted to the host latched by the scheduler, then lowered to the next component. Only exceptions being streams which flow guest to guest as being part of same 'island'
Lemme investigate the composition route fully and check if it works-out. (main risks being loosing out on trap recovery)
sansmoraxz edited a comment on issue #15105:
if you don't need data to go through the host
My current model is for most values outputs from one node are lifted to the host latched by the scheduler, then lowered to the next component. Only exceptions being streams which flow guest to guest as being part of same 'island'
Lemme investigate the composition route fully and check if it works-out. (main risks being loosing out on trap recovery and value captures for previews)
sansmoraxz commented on issue #15105:
Ok investigated a bit more.
Composition works as a perf option (Direct wasmtime, dynamic Val's 2,699 ms with 1,635 MiB; vs 114 ms with 137 MiB)
However there are some nuances here:
- latching and change detection need the value in the host, and reading just one port brings most of the
Valcost back.- A trap takes down the entire composed group, while current routing only faults the individual node. This behaviour makes sense for streams, while I was trying to avoid this for ordinary value data transports.
- While testing the composed group faulted at run 249,999 with
resource table has no free keysWill doc this on my side. Val ports work fine for small data, but for larger data with performance significance either
streamor use the host declared handles for sharing.
sansmoraxz commented on issue #15105:
Also fyi typed APIs don't really fit my repo's usecase. Port types come from components loaded at runtime, but TypedFunc needs Rust types at host compile time.
Last updated: Nov 19 2026 at 20:05 UTC