Skip to content

JS effect marshaller overflows the host stack when recursion is nested under Array #1346

Closed

Description

@jasisz

What you did

Run the program below on the JS lane, then build and run it on the native lane:

bend main.bend
bend main.bend -o main && ./main

What happened

On the JS lane, a depth of 5,000 prints ok, but 10,000 fails with:

bend: memory fault (machine stack overflow?)

The native lane prints ok at depth 20,000. A control with the same 10,000-deep
recursive ADT but a direct next: Tree field also prints ok on JS. The failure
appears only when the recursive occurrence is under Array.

The generated marshaller makes a direct recursive field iterative, but the
wrapped occurrence remains a host call inside the array converter:

"kids": ((a) => (a.forEach((x, i) => a[i] = $0m0(x)), a))(v["kids"])

This looks distinct from the JS non-tail-call limitation in WONTFIX.txt
(#798/#802): grow is tail-recursive and completes, while the host stack grows
only in compiler-generated marshalling at the effect boundary. Direct recursive
marshaller paths are already emitted as a loop, and #1304 tested a 50,000-deep
recursive Nat round trip; nesting that path under Array bypasses the loop.

Reproduced on current main at 565d7fdec289b1f2f5f5037bb58b5afb6738ff1d.

The files

main.bend:

import Base

type Tree is Type:
  Leaf{}
  Node{n: Nat, kids: Array<Tree>}

def grow(n: Nat, tree: Tree) -> Tree:
  match n:
    case 0n:
      tree
    case 1n+p:
      grow(p, Node{0n, ALeaf{tree}})

law touch:
  for tree: Tree
  IO(Unit)

def touch(tree):
  import "./main.c"
  import "./main.js"

def main() -> IO(Unit):
  do IO<Unit>:
    u : Unit <- touch(grow(U32.to_nat(20000), Leaf{}))
    IO.print("ok")

#|ok

main.js:

function touch(tree) {
  return {$: CID(Unit)};
}
io_eff(CID(touch), touch);

main.c:

Term touch_run(Env e, Term* f, IoWork* w) {
  return term_pak(CID(Unit), 0);
}
static void __attribute__((constructor)) touch_use(void) {
  io_eff(CID(touch), touch_run, 0);
}

bend --version

bend 2.0.35

uname -sm

Darwin arm64

clang --version (the first line)

Apple clang version 21.0.0 (clang-2100.0.123.102)

Found and reproduced by Codex (OpenAI).

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