garage44.eu/jeroen/frits

logclone: git clone https://garage44.eu/jeroen/frits.git

cartopolis-agent · 2026-11-26T20:19:52Z

feat(frits): built-in methods cost fuel by the size of what they copy

A host running uploaded scripts needs a slice to bound the work it does,
not only its instructions. Every built-in method cost one unit whatever
its input: a slice of 20,000 instructions could copy a 30,000-item list
20,000 times, or build gigabytes of string with repeat, before it paused.

A call now also costs one unit per 8 items or 64 string bytes it takes
and gives back, n log n for sort and the walked size for ==; string
concatenation costs its bytes. Constant-time methods stay at one.
crates/frits/src/stdlib.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++
 crates/frits/src/tests.rs  | 39 +++++++++++++++++++++++++++++++
 crates/frits/src/vm.rs     |  8 ++++++-
 docs/design.md             |  6 +++--
 4 files changed, 108 insertions(+), 3 deletions(-)

diff --git a/crates/frits/src/stdlib.rs b/crates/frits/src/stdlib.rs
index 7a3a212..14e55ec 100644
--- a/crates/frits/src/stdlib.rs
+++ b/crates/frits/src/stdlib.rs
@@ -77,6 +77,64 @@ impl Std {
     }
 }
 
+/// Values copied, compared or moved per unit of fuel by a built-in method.
+const ITEMS_PER_FUEL: u64 = 8;
+/// String bytes copied or scanned per unit of fuel.
+pub const BYTES_PER_FUEL: u64 = 64;
+
+/// How much work one value is to a method that walks it once: its items, or
+/// its bytes for a string.
+fn work(heap: &Heap, strings: &[Rc<str>], v: Value) -> u64 {
+    match v {
+        Value::Static(i) => strings.get(i as usize).map_or(0, |s| s.len() as u64) / BYTES_PER_FUEL * ITEMS_PER_FUEL,
+        _ => match heap.get(v) {
+            Some(Obj::Str(s)) => s.len() as u64 / BYTES_PER_FUEL * ITEMS_PER_FUEL,
+            Some(Obj::List(x) | Obj::Map(x)) => x.len() as u64,
+            Some(Obj::Record(x) | Obj::Variant(_, x) | Obj::Closure(_, x)) => x.len() as u64,
+            None => 0,
+        },
+    }
+}
+
+/// Items in a value all the way down, stopping once past `cap`.
+fn deep_work(heap: &Heap, v: Value, cap: u64) -> u64 {
+    let mut n = 0;
+    let mut stack = vec![v];
+    while let Some(v) = stack.pop() {
+        n += 1;
+        if n > cap {
+            break;
+        }
+        match heap.get(v) {
+            Some(Obj::List(x) | Obj::Map(x)) => stack.extend_from_slice(x),
+            Some(Obj::Record(x) | Obj::Variant(_, x)) => stack.extend_from_slice(x),
+            _ => {}
+        }
+    }
+    n
+}
+
+/// The fuel a call of `f` costs beyond its own instruction, from the sizes of
+/// what it took (`a`) and gave back (`out`), so that copying, sorting or
+/// comparing a big value is not as cheap as adding two numbers. Without it a
+/// slice of 20,000 instructions could copy a list of 30,000 items 20,000 times.
+pub fn cost(f: Std, heap: &Heap, strings: &[Rc<str>], a: &[Value], out: Value) -> u64 {
+    use Std::*;
+    let items = match f {
+        // Constant time whatever the size.
+        ListGet | ListFirst | ListLast | MapLen | MapHas | MapGet | IntAbs | IntMin | IntMax | VecAdd
+        | VecSub | VecScale | VecDiv | VecDot | VecCross | VecLength | VecNormalize | VecDistance | VecLerp
+        | MapNew => 0,
+        ListSort => {
+            let n = work(heap, strings, a[0]);
+            n * (64 - n.leading_zeros() as u64)
+        }
+        Equal => deep_work(heap, a[0], u64::MAX >> 1).min(deep_work(heap, a[1], u64::MAX >> 1)),
+        _ => a.iter().map(|v| work(heap, strings, *v)).sum::<u64>() + work(heap, strings, out),
+    };
+    items / ITEMS_PER_FUEL
+}
+
 const NONE: Value = Value::Tag(0);
 
 fn some(heap: &mut Heap, v: Value) -> Value {
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
index 2b8ce4d..438c849 100644
--- a/crates/frits/src/tests.rs
+++ b/crates/frits/src/tests.rs
@@ -616,6 +616,45 @@ fn a_costly_host_call_spends_fuel() {
     assert_eq!(rt.get(pid).unwrap().state.0, ["done"]);
 }
 
+#[test]
+fn copying_a_big_value_costs_by_its_size() {
+    // Each `push` on a `var` copies the list: n pushes copy n²/2 items, which
+    // must cost more than the n instructions the loop spends.
+    let run = |n: i64| {
+        let mut rt = Runtime::new(platform());
+        rt.limits.memory = 4 * 1024 * 1024;
+        let src = format!(
+            "script / Out\non go() {{\n var xs: List<Int> = []\n var i = 0\n while i < {n} {{ xs.push(i)\n i += 1 }}\n Out.say(\"{{len(xs)}}\")\n }}"
+        );
+        let m = rt.platform.compile(&src).unwrap();
+        let pid = rt.spawn(m, Log::default());
+        rt.post(pid, "go", Vec::new());
+        let mut slices = 0;
+        while rt.get(pid).unwrap().has_work() {
+            rt.tick();
+            slices += 1;
+        }
+        let p = rt.get(pid).unwrap();
+        assert_eq!(p.state.0, [n.to_string()], "{:?}", p.status);
+        slices
+    };
+    // 20,000 pushes copy 200 million items: far more than one slice.
+    assert!(run(20_000) > 500, "copying was nearly free");
+    assert!(run(100) <= 1);
+
+    // Joining and repeating strings counts their bytes.
+    let mut rt = Runtime::new(platform());
+    rt.limits.memory = 4 * 1024 * 1024;
+    let m = rt
+        .platform
+        .compile("script / Out\non go() {\n var i = 0\n while i < 2000 { let s = \"x\".repeat(1000000)\n i += len(s) / 1000000 }\n Out.say(\"done\")\n }")
+        .unwrap();
+    let pid = rt.spawn(m, Log::default());
+    rt.post(pid, "go", Vec::new());
+    rt.tick();
+    assert_eq!(rt.get(pid).unwrap().status, Status::Paused, "2 GB of string in one slice");
+}
+
 #[test]
 fn kept_values_survive_a_new_version_of_the_script() {
     let mut rt = Runtime::new(platform());
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
index 1debd04..bd492ac 100644
--- a/crates/frits/src/vm.rs
+++ b/crates/frits/src/vm.rs
@@ -607,6 +607,7 @@ impl<S> Process<S> {
                         if total > mem_limit {
                             fail!(format!("out of memory: a {} KiB string", total / 1024));
                         }
+                        fuel = fuel.saturating_sub(total as u64 / crate::stdlib::BYTES_PER_FUEL);
                         let mut out = String::with_capacity(total);
                         for v in parts {
                             out.push_str(self.heap.str(*v, &m.strings));
@@ -674,8 +675,13 @@ impl<S> Process<S> {
                     Op::Std { f, base: b, dst } => {
                         let s = base + b as usize;
                         let args = &self.regs[s..s + f.arity()];
+                        let args: [Value; 3] = std::array::from_fn(|i| args.get(i).copied().unwrap_or(Value::Unit));
+                        let args = &args[..f.arity()];
                         match crate::stdlib::call(f, &mut self.heap, &m.strings, args, mem_limit) {
-                            Ok(v) => r!(dst) = v,
+                            Ok(v) => {
+                                r!(dst) = v;
+                                fuel = fuel.saturating_sub(crate::stdlib::cost(f, &self.heap, &m.strings, args, v));
+                            }
                             Err(e) => fail!(e),
                         }
                     }
diff --git a/docs/design.md b/docs/design.md
index e4760e6..0cc07bf 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -308,8 +308,10 @@ Known gaps in what is built:
   after it; it sees that global as zero/empty rather than an error.
 - Keywords cannot be names (`on`, `in`, `type`…): a parameter called `on` is a
   syntax error.
-- Fuel counts instructions; a host function's cost counts only when the host
-  charges it (`cx.charge`).
+- Fuel counts instructions, plus the size of what a built-in method copies,
+  sorts or compares (one unit per 8 items or 64 string bytes, `stdlib::cost`),
+  so a slice cannot copy a big list thousands of times for free. A host
+  function's cost counts only when the host charges it (`cx.charge`).
 - A list or map changed through `push` or `set` is copied each time: building
   a list of n items one push at a time costs n²/2 copies. `map` and `filter`
   build in place.