Skip to content

Metal: non-tail recursion under a bang faults at 1023 list elements; CPU completes through 100000 #1393

Description

@Eziowl

A ! call whose body recurses non-tail over a list (Base's List.append, one frame per element of its first list) dies on the Metal lane with bend: memory fault (machine stack overflow?) once the list has 1023 elements. 1022 passes in the recorded runs. The same binary with --gpu off completes at the tested lengths through 100000. There are no parallel calls inside the !; it is one sequential def.

Program (deep.bend)

import Base

# [n-1, ..., 1, 0], built with a tail loop.
def Gen(n: Nat, +k: U32, acc: List<&2, U32>) -> List<&2, U32>:
  match n:
    case 0n:
      acc
    case 1n+p:
      Gen(p, (k + 1 : U32), k <> acc)

# Sum with a tail loop.
def Sum(xs: List<&2, U32>, +acc: U32) -> U32:
  match xs:
    case Nil{}:
      acc
    case Con{h, t}:
      Sum(t, (acc + h : U32))

# The only non-tail recursion: List.append over n elements.
def Deep(n: Nat) -> U32:
  xs = Gen(n, 0, [])
  ys = List.append(&2, U32, xs, [7])
  Sum(ys, 0)

def Run(m: Maybe<&2, U32>) -> IO(Unit):
  match m:
    case Some{n}:
      IO.print(U32.show(Deep!(U32.to_nat(n))))
    case None{}:
      IO.die(Unit, 2, "usage: deep <n>")

def Args(args: List<String>) -> IO(Unit):
  match args:
    case Con{_, Con{n, _}}:
      Run(U32.read(n))
    case _:
      IO.die(Unit, 2, "usage: deep <n>")

def main() -> IO(Unit):
  do IO<Unit>:
    args : List<String> <- IO.args()
    Args(args)

Commands and output

$ bend deep.bend -o deep
$ ./deep 1022
521738
[exit 0]
$ ./deep 1023
bend: memory fault (machine stack overflow?)
[exit 1]
$ ./deep 1023 --gpu off
522760
[exit 0]
$ ./deep 100000
bend: memory fault (machine stack overflow?)
[exit 1]
$ ./deep 100000 --gpu off
704982711
[exit 0]

The 1022/1023 boundary is exact and deterministic (3 of 3 runs each). The program and these commands are the whole repro.

Relation to earlier issues

Environment

  • bend 2.0.34 (bend version). Later releases are untested here, including 2.0.36; this report makes no claim about their behavior.
  • macOS 26.5.2 (25F84), Apple M3 Ultra, Darwin arm64; clang on PATH: Apple clang 21.0.0 (clang-2100.1.1.101).
  • Built with bend deep.bend -o deep; the .gpu program sits beside the binary.

Activity

  1. Giulio2002 commented on Oct 8, 2026

    @Giulio2002
    Contributor

    The same fault reproduces on the CUDA lane, at the same boundary — this doesn't look Metal-specific after all. Measured on Linux x86_64, bend 2.0.36 (commit 1d895ca), NVIDIA RTX PRO 6000 Blackwell (driver 595.91.07, CUDA 13.2), bun 1.4.2, clang 21.

    What you did

    Non-tail recursion under a bang, with the list built tail-recursively so construction is not the source of depth (the recursion being tested is the sum walk):

    import Base
    
    def lsum(xs: List<&1, U32>) -> U32:
      match xs:
        case Nil{}:
          0
        case Con{h, t}:
          (h + lsum(t) : U32)
    
    def build(n: Nat, acc: List<&1, U32>) -> List<&1, U32>:
      match n:
        case 0n:
          acc
        case 1n+p:
          build(p, Con{1, acc})
    
    def probe(n: Nat) -> U32:
      lsum(build(n, Nil{}))
    
    def main() -> IO(Unit):
      do IO<Unit>:
        c : U32 = probe!(2000n)
        IO.print(U32.show(c))

    What happened

    By depth, on the same binary:

    list length ./t --gpu off (CPU pool) ./t (CUDA)
    1000 / 1022 correct correct
    1023 correct bend: memory fault (machine stack overflow?)
    1024 … 1,000,000 correct bend: memory fault (machine stack overflow?)

    The 1023/1024 boundary matches this issue's Metal threshold exactly, 10/10 deterministic at n=2000 — so the per-lane device stack cap looks shared by (or mirrored in) the CUDA build, not a Metal quirk. The CPU pool completes through 1,000,000 elements, as here.

    For completeness, two adjacent CUDA-path behaviors checked while there (both clean, both negative results for their respective open issues): with --gpu 512MB/--gpu 1GB caps, exceeding the device heap reports the graceful bend: out of memory: run again with a bigger span, as in --gpu 8GB and exits 1 (#1300's fault/hang class did not reproduce on CUDA at the allocation-failure points I could construct); and a large [0 : U32^28n] allocation inside a bang does run on the device (visible in nvidia-smi) but takes ~20 s of host CPU time where --gpu off does the same work in 1.2 s wall — possibly the same per-lane serialization, possibly host-side page servicing; I did not chase that down far enough to call it a finding.

    Found by an automated AI-model differential-testing campaign against bend 2.0.36; the threshold table and determinism count were re-measured in isolation.

  2. wakamex commented on Oct 10, 2026

    @wakamex
    Contributor

    Same limit on CUDA here, but whether you hit it depends on how many tasks the bang spreads to. While some lanes are free, a lane can recurse much deeper than 1,023. Once every lane has a task, any recursion past about 1,024 calls faults. Measured on main (d5fe656), RTX 3090, driver 615.71, CUDA 13.1.

    This forks 2^d leaves under one bang. Leaf i builds a list of n copies of i and sums it with the same non-tail lsum as above:

    import Base
    
    type T is Type:
      Leaf{x: U32}
      Node{l: T, r: T}
    
    def lsum(xs: List<&1, U32>) -> U32:
      match xs:
        case Nil{}:
          0
        case Con{h, t}:
          (h + lsum(t) : U32)
    
    def build(n: Nat, +v: U32, acc: List<&1, U32>) -> List<&1, U32>:
      match n:
        case 0n:
          acc
        case 1n+p:
          build(p, v, Con{v, acc})
    
    def leaves(+d: Nat, +i: U32, +n: Nat) -> T:
      match d:
        case 0n:
          Leaf{lsum(build(n, i, Nil{}))}
        case 1n+e:
          x y = leaves(e, U32.mul(i, 2), n) leaves(e, U32.add(U32.mul(i, 2), 1), n)
          Node{x, y}
    
    def total(t: T) -> U32:
      match t:
        case Leaf{x}:
          x
        case Node{l, r}:
          U32.add(total(l), total(r))
    
    def go(md: Maybe<&2, Nat>, mn: Maybe<&2, Nat>) -> IO(Unit):
      match md mn:
        case Some{+d} Some{+n}:
          IO.print(U32.show(total(leaves!(d, 0, n))))
        case _ _:
          IO.print("usage: deep log2_leaves n")
    
    def dispatch(args: List<String>) -> IO(Unit):
      match args:
        case Con{p, Con{d, Con{n, Nil{}}}}:
          go(Nat.read(d), Nat.read(n))
        case _:
          IO.print("usage: deep log2_leaves n")
    
    def main() -> IO(Unit):
      do IO<Unit>:
        args : List<String> <- IO.args()
        dispatch(args)

    ./deep D N --gpu 8GB, each list N long:

    Leaves under the bang N = 1,000 N = 1,100 N = 20,000
    1 ok ok ok
    4,096 ok ok ok
    8,192 ok memory fault memory fault
    16,384 ok memory fault memory fault

    --gpu off gets every cell right, and a 20 GB heap faults the same way. The 3090 has 82 SMs, so CUBE_LOG is 6 and the bag is 128 << 6 = 8,192 lanes (comp.ts#L5019): the fault starts exactly when there are as many leaves as lanes. The single-leaf row is interesting too: the same lsum 20,000 deep works as one leaf of leaves!, but probe!(2000n) from the comment above still faults on this commit. So I'd guess the fork-free case, or the case where every lane is busy, runs on the fixed lane stack (STAK_LEN 2^11 words, comp.ts#L3501), and WL_ROOM posts ERR_DEEP when it fills (comp.ts#L3423). I haven't confirmed that though.

    This is what caps the batch size in a real workload. I run nanoGPT inference as a batch of independent generations, one per leaf, over shared weights (bend-bench ML.md). It works up to 4,096 sequences and faults within a second from 8,192, at any heap size, while the CPU runs 8,192 fine. So the GPU never gets past half its lanes on that workload.

    Two smaller things:

    • The message for ERR_DEEP, "memory fault (machine stack overflow?)", sounds like a heap or host problem. Something like "a GPU lane's stack is full: recursion deeper than about 1,000 calls" would have saved me a few rounds of heap sizes.
    • The same limit hits joins, not just leaves. My first batch appended each half's list of results at every join, and that recursion overflowed at 2,048 sequences. Returning a tree instead fixed it.
  3. Lorenzobattistela commented on Oct 21, 2026

    @Lorenzobattistela
    Collaborator

    Reopening: the fix from #1439 is removed in #1809.

    lane_spill joins the device code of every ! program, so it made the Metal GPU program's build (./main +RTS --gpu-build, part of bend -o) 17% slower: 0.257 s → 0.300 s on an M4 mini. That pushed the perf gate's COMPILER column past its 1.15× limit (symreg 1.16×, merkle 1.17×). I bisected it over v2.0.37..main, and it reproduces on a second mini and on an M4 Pro. The data is in #1809.

    The fault at 1023 frames is back until the spill returns in a form that only programs needing it pay for, for example built into the device program only when a ! actually reaches deep non-tail recursion. tests/compile/bang_lane_spill.bend from #1439 is the test to bring back with it.

  4. jkbennitt commented on Nov 10, 2026

    @jkbennitt
    Contributor

    Confirming this still reproduces on Bend 2.0.40 (bend version), Apple M4 / Metal 4, macOS 27.0.1 (Darwin 27.0.0 arm64, Apple clang 21.0.0). I hit it from a slightly different shape than the original sequential List.append: a divide-and-conquer map that mid-splits and then List.appends the two halves, inside a nearest-reference argmin. That looks like the join-append case wakamex mentioned (overflow around 2,048 sequences). It came up while benchmarking a U-NSGA-III implementation in Bend.

    With 3 reference points, N = 2046 crashes (first half has 1023 elements) and N = 2045 passes (first half 1022). The same binary with --gpu off prints the expected length at both sizes. Two GPU runs at N = 2046 both exited 1 with bend: memory fault (machine stack overflow?).

    Standalone 37-line repro (N = 2046, R = 3)
    import Base
    
    def gen(+n: Nat) -> List<&2, F32>:
      match n:
        case 0n:
          Nil{}
        case 1n+k:
          F32.from_nat(n) <> gen(k)
    
    def nearest(+f: F32, refs: List<&2, F32>, +i: Nat, +bi: Nat, +bd: F32) -> Nat:
      match refs:
        case Nil{}:
          bi
        case +w <> ws:
          +d = F32.abs(F32.sub(f, w))
          nearest(f, ws, 1n+i, Bool.pick(Nat, F32.is_lt(d, bd), i, bi), Bool.pick(F32, F32.is_lt(d, bd), d, bd))
    
    def map.go(+refs: List<&2, F32>, +fuel: Nat, pts: List<&2, F32>) -> List<&2, Nat>:
      match fuel pts:
        case 0n Nil{}:
          Nil{}
        case 0n p <> rest:
          nearest(p, refs, 0n, 0n, 1000000000.0) <> map.go(refs, 0n, rest)
        case 1n+p Nil{}:
          Nil{}
        case 1n+p h <> Nil{}:
          nearest(h, refs, 0n, 0n, 1000000000.0) <> Nil{}
        case 1n+p h <> t:
          +all = {h <> t : List<&2, F32>}
          +mid = Nat.div(List.length(&2, F32, all), 2n)
          lo hi = map.go(refs, p, List.take(&2, F32, all, mid)) map.go(refs, p, List.drop(&2, F32, all, mid))
          List.append(&2, Nat, lo, hi)
    
    def main() -> IO(Unit):
      do IO<Unit>:
        xs : List<&2, Nat> = map.go!(gen(3n), 2046n, gen(2046n))
        IO.print(Nat.show(List.length(&2, Nat, xs)))
    $ bend assoc.bend -o assoc
    $ ./assoc +RTS --threads 1
    bend: memory fault (machine stack overflow?)
    $ ./assoc +RTS --threads 1 --gpu off
    2046
    

    Changing both 2046n to 2045n in main succeeds on the GPU and prints 2045.

  5. wakamex commented on Nov 14, 2026

    @wakamex
    Contributor

    Thanks for the repro. It's the same cause as the original report: List.append isn't tail-recursive, so inside a ! every element of the first list is a frame on the lane's 2,048-word stack, 2 words each, and a 1,023-element half overflows it. I see the same boundary on CUDA (RTX 3090) with my own divide-and-conquer append: 2,045 runs, 2,046 faults.

    #1819 makes that shape finish: 2,046 and 100,000 elements on CUDA, and 100,000 on an M4 in 0.19 s. I just pushed a rework there for Lorenzo's review, and it's up to him. Until it lands, writing the append as two tail loops (reverse the first list, then move it onto the second) keeps the stack flat, as nuxyel did for their matrix product.

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