Skip to content

§14.3 INVARIANT 5: may_suspend is not part of the fn type, so every call through a callable parameter polls for cancellation (4.5× on a fold) #2511

Closed

Description

@ehartford

Spec (§14.3 INVARIANT 5): "may_suspend is part of callable type information for function pointers, closures, trait and dyn callables, callbacks, and every other indirect-call surface. … the typing burden appears only when a function becomes a value." and "Programmers do not declare or annotate may_suspend. The compiler computes it internally."

Implementation: src/SemaCheck.w callable_value_may_suspend: "A parameter's value is the caller's: at the call site (site) it is unknown, so it may" — if self.callable_param_idents.contains(expr): return site. A call through a callable parameter is therefore always a may-suspend call site, whatever flows into it, and MIR (emit_cancelled_return_check, src/MirLower.w ~10754) emits a FIBER_WAIT_CANCELLED poll plus the cancelled-return switch after every such call. The fn type carries no may_suspend; the body is compiled once for every caller.

Cost (measured 2026-10-20, the installed compiler v0.15.3.0-g07900708d, -O3, 4,000,000 i64 elements, best of 7, Apple Silicon):

shape ns
J concrete ListIter.next() loop, no callable 1,858,292
G generic I: Iter[i64] loop over a user wrapper 1,857,958
G2 generic I: Iter[i64] loop over ListIter 1,857,708
H fn(i64, i64) -> i64 parameter, a named fn passed 8,369,625
H2 the same, a closure passed 9,308,292

A generic trait-bound call costs nothing; a call through a callable parameter costs 4.5×. llvm-objdump -d -r of std.traits' iter_fold instance (inlined into its caller) shows the loop body is ldr; add; adds followed by two out-of-line calls per element: ARM64_RELOC_BRANCH26 _with_fiber_wait_cancelled and _with_fiber_set_cancelled_return. End to end, v.iter() |> map |> filter |> fold through std.traits' bodies (a user Iter[T] wrapper forces §13.3's trait path) is 35 ms against 4.0 ms through the intrinsics and 1.9 ms as a hand loop.

Expected: per the spec, f: fn(i64, i64) -> i64 is a callable type whose may_suspend the compiler computes from the values that become it; a body whose callable parameter is sync has no suspension point at the call and no poll. One shape that satisfies the spec: may_suspend is a component of the fn type (as move-ness already is, §12), so a body is instantiated per may_suspend-ness of its callable parameters like any other type parameter, and a call through a sync callable compiles to a plain call.

Why it matters now: #2220's ruling (Option 2) moves the iterator adapters from codegen intrinsics to std.traits' With bodies, gated on the bodies reaching the intrinsic's code (same IR or a pipeline benchmark within 2%). Every adapter body takes its closure as a callable parameter, so this is the gap that gate measures; the generic-bound next() is already free.

Repro: test-shaped program in the issue's first comment (pipeline_bench3.w).

Activity

  1. ehartford commented on Oct 21, 2026

    @ehartford
    ContributorAuthor

    The repro (with build pipeline_bench3.w -O3):

    // #2220 step 1, the cost matrix: which call shape carries the per-call
    // cancellation poll (§14.3 invariant 5) and what it costs.
    use std.time
    use std.collections.ListIter
    
    type Wrap ephemeral { inner: ListIter[i64] }
    impl Iter[i64] for Wrap:
        mut fn next() -> Option[i64]: self.inner.next()
    
    // G: generic over a bound trait, no callable parameter.
    fn sum_bound[I: Iter[i64]](iter: I) -> i64:
        var i = iter
        var acc: i64 = 0
        while true:
            match i.next():
                None => break
                Some(x) => acc = acc + x
        acc
    
    // H: concrete iterator, callable parameter.
    fn fold_param(v: &List[i64], f: fn(i64, i64) -> i64) -> i64:
        var i = v.iter()
        var acc: i64 = 0
        while true:
            match i.next():
                None => break
                Some(x) => acc = f(acc, x)
        acc
    
    // J: concrete iterator, no callable: the floor.
    fn hand(v: &List[i64]) -> i64:
        var i = v.iter()
        var acc: i64 = 0
        while true:
            match i.next():
                None => break
                Some(x) => acc = acc + x
        acc
    
    fn add(a: i64, b: i64) -> i64: a + b
    
    fn g_path(v: &List[i64]) -> i64: sum_bound(Wrap { inner: v.iter() })
    fn g_direct(v: &List[i64]) -> i64: sum_bound(v.iter())
    fn h_path(v: &List[i64]) -> i64: fold_param(v, add)
    fn h_closure(v: &List[i64]) -> i64: fold_param(v, (a, b) => a + b)
    
    fn best(f: fn(&List[i64]) -> i64, v: &List[i64], name: &str):
        var b: i64 = 0
        var s: i64 = 0
        for round in 0..7:
            let t0 = now_ns()
            s = f(v)
            let t1 = now_ns()
            if b == 0 or t1 - t0 < b: b = t1 - t0
        print(f"{name}: {b} ns, checksum {s}")
    
    fn main:
        var v: List[i64] = List.new()
        for i in 0..4_000_000: v.push(i)
        best(hand, &v, "J floor: concrete next, no callable")
        best(g_path, &v, "G generic I: Iter over Wrap")
        best(g_direct, &v, "G2 generic I: Iter over ListIter")
        best(h_path, &v, "H fn parameter (named fn)")
        best(h_closure, &v, "H2 fn parameter (closure)")
    
  2. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): does not reproduce; 3a45024 (#2538) made a callable parameter suspend only when some caller hands it a callable that may. A fold over a plain fn(i64, i64) -> i64 parameter no longer polls:

    $ cat main.w
    fn fold(xs: &List[i64], f: fn(i64, i64) -> i64) -> i64:
        var acc: i64 = 0
        for x in xs: acc = f(acc, x)
        acc
    fn add(a: i64, b: i64) -> i64: a + b
    fn main:
        let xs: List[i64] = [1, 2, 3]
        print(fold(&xs, add))
    $ with run main.w
    6
    $ with check main.w --dump-mir   # task_cancel_point is defined; no body calls it
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions