Skip to content

JS backend: String.split/String.length recurse per character and overflow the JS stack on ~10k+ char strings (found by DeepSeek V4.1 Flash) #798

Closed

Description

@FariaDev

Summary

In the JS backend, String.split and String.length are emitted as per-character recursions. On inputs above ~10k characters (Node/V8) or ~15–20k (Bun), calling them throws RangeError: Maximum call stack size exceeded at runtime — not at check time. The existing trampoline (run_loop/run_jump) does not help because the recursive call is not in tail position (it is evaluated eagerly as an argument). String.take is fine (native slice), so this seems specific to the recursively-defined primitives.

Minimal repro

split-recursion.bend:

import Base

def parts(s: String) -> List<&2, String>:
  String.split(s, ',')

def len(s: String) -> Nat:
  String.length(s)

def take5(s: String) -> String:
  String.take(s, 5n)

Built with bun + the bend2 plugin (~/.bend/current/bend2/main.ts, target browser/esm, no minify) and called from JS with 'x'.repeat(n):

n String.split (Bun / Node) String.length (Bun / Node) String.take (Bun / Node)
5 000 ok / ok ok / ok ok / ok
10 000 ok / RangeError ok / RangeError ok / ok
15 000 ok / RangeError ok / RangeError ok / ok
20 000 RangeError / RangeError ok / RangeError ok / ok
100 000 RangeError / RangeError RangeError / RangeError ok / ok

Generated code (from the artifact), showing the non-tail recursion in $String$split$:

function $String$split$(s_0, sep_0) {
  if (s_0 === "") { return { $: "Con", ["head"]: "", ["tail"]: { $: "Nil" } }; }
  const h_0 = s_0.codePointAt(0) > 65535 ? s_0.slice(0, 2) : s_0[0];
  const t_0 = s_0.codePointAt(0) > 65535 ? s_0.slice(2) : s_0.slice(1);
  const h_1 = h_0;
  return run_jump($String$split$fin$, [h_1, run_loop($String$split$(t_0, sep_0)), run_loop($Char$is_eq$(h_1, sep_0))]);
}

Runner used (works under both runtimes; build part needs Bun):

import core from './split-recursion.core.js';
const count = (xs) => { let n = 0; for (let l = xs; l && l.$ === 'Con'; l = l.tail) n++; return n; };
for (const n of [5000, 10000, 15000, 20000, 100000]) {
  try { count(core.parts('x'.repeat(n))); console.log(n, 'split ok'); }
  catch (e) { console.log(n, 'split ERRO:', e.message); }
}

Real-world impact

An Electron app's logic ported to Bend uses String.split to frame a JSON-RPC line stream from a child process. Its buffers reach MBs (an 11 MB session dump). The generated artifact threw RangeError: Maximum call stack size exceeded inside $String$split$, which silently killed the response handling and surfaced as a connection timeout — extremely hard to trace from the app side. Any Bend program processing user data as strings (logs, JSON lines, pasted text, file contents) will hit this at a few KB–10k chars.

Environment

  • bend --version → bend 2.0.5
  • Bun 1.4.2, Node 26.8.2, macOS arm64
  • Artifact from the bend2 plugin, target browser, format esm, no minify

Possible directions

Attribution

Found and reproduced by an AI coding agent — DeepSeek V4.1 Flash (via OpenCode) — while porting a real app (an Electron study desk) to Bend, at the request of the project owner. Numbers above are from this machine; happy to test a patch or provide the ported app's framing module as an additional test case.

Activity

  1. aron-intframe commented on Sep 18, 2026

    @aron-intframe

    Reproduced on current main (0b7e2b1, VERSION = "2.0.5"), compiling through the loader in bend2/main.ts and running the emitted JS under Node 20.20 and Bun 1.4.2. Same numbers as yours: String.split and String.length throw RangeError at 10k chars on Node and at 20k/100k on Bun.

    Two things to add.

    1. String.take is not special, and it is not native. In base.bend it has the exact same shape as split/length (SCon{h, String.take(t, p)}, non-tail), and the emitter has no intrinsic for it. It only looked fine because your test calls String.take(s, 5n): recursion depth is n, not the string length. Calling it with n = string length overflows at the same sizes:

    runtime: node v20.20.2
    10000 String.take 5 ok 5
    10000 String.take n ERR RangeError: Maximum call stack size exceeded
    100000 String.take n ERR RangeError: Maximum call stack size exceeded
    

    Same family at 100k chars on Node: String.to_upper and String.to_list throw as well. String.reverse, String.drop, String.trim are fine because their self-call is already in tail position (they go through run_jump). String.append is fine because comp.ts maps it to a native (string_append: { JS: "($0 + $1)" }), so there is precedent for the native route you suggest.

    2. Workaround that works today, no compiler change. Write the two functions accumulator-style so the self-call is in tail position; the JS backend then emits run_jump and the trampoline keeps the stack flat. Mutual recursion is not allowed and match cannot scrutinize a computed value, so the per-char decision goes into a non-recursive step helper that returns the new state as a tuple:

    def Str.length.go(s: String, acc: Nat) -> Nat:
      match s:
        case SNil{}:
          acc
        case SCon{h, t}:
          Str.length.go(t, 1n+acc)
    
    def Str.length(s: String) -> Nat:
      Str.length.go(s, 0n)
    
    # state = (current piece, reversed; pieces so far, reversed)
    def Str.split.step(h: Char, st: String & List<&2, String>, cut: Bool) -> String & List<&2, String>:
      (cur, acc) = st
      match cut:
        case True{}:
          (SNil{}, String.reverse(cur) <> acc)
        case False{}:
          (SCon{h, cur}, acc)
    
    def Str.split.fin(st: String & List<&2, String>) -> List<&2, String>:
      (cur, acc) = st
      List.reverse(&2, String, String.reverse(cur) <> acc)
    
    def Str.split.go(s: String, +sep: Char, st: String & List<&2, String>) -> List<&2, String>:
      match s:
        case SNil{}:
          Str.split.fin(st)
        case SCon{+h, t}:
          Str.split.go(t, sep, Str.split.step(h, st, Char.is_eq(h, sep)))
    
    def Str.split(s: String, +sep: Char) -> List<&2, String>:
      Str.split.go(s, sep, (SNil{}, Nil{}))
    

    Checks clean. Output matches String.split from Base on the edge cases I tried (empty string, leading/trailing/adjacent separators, astral chars), and it handles your 11 MB case:

    runtime: node v20.20.2
    same ""            [""]
    same ","           ["",""]
    same ",a,,b,"      ["","a","","b",""]
    same "😀,x😀y,,"    ["😀","x😀y","",""]
    10000    Str.split (loop) ok 101     5ms     String.split(Base) ERR RangeError
    100000   Str.split (loop) ok 1001    14ms    String.split(Base) ERR RangeError
    1000000  Str.split (loop) ok 10001   133ms
    11000000 Str.split (loop) ok 110001  1593ms
    11000000 Str.length(loop) ok 11000000n 239ms
    

    Emitted JS for the loop version, for comparison with the one in your report:

    function $Str$split$go$(s_0, sep_0, st_0) {
      if (s_0 === "") {
        return run_jump($Str$split$fin$, [st_0]);
      } else {
        const h_0 = (s_0.codePointAt(0) > 0xFFFF ? s_0.slice(0, 2) : s_0[0]);
        const t_0 = (s_0.codePointAt(0) > 0xFFFF ? s_0.slice(2) : s_0.slice(1));
        const h_1 = h_0;
        return run_jump($Str$split$go$, [t_0, sep_0, run_loop($Str$split$step$(h_1, st_0, run_loop($Char$is_eq$(h_1, sep_0))))]);
      }
    }

    For Base itself the same rewrite would fix String.length/String.split/String.take/String.to_upper/String.to_lower/String.to_list/String.from_list on the JS lane without touching the emitter; a string_length/string_split entry next to string_append in OPERATIONS would be the faster route for the two hot ones.

  2. FariaDev commented on Sep 18, 2026

    @FariaDev
    Author

    Thanks @aron-intframe — confirmed on our side, and the take correction was spot on: our own probe had the same blind spot (small n), which is exactly why we had cleared it. Independent run here (Node v26.8.2, artifact from the same loader, unminified):

    • String.take(s, 5n) ok at 100k; String.take(s, n) → RangeError at 10k; String.length → RangeError at 10k; String.to_upper / String.to_list → RangeError at 100k.
    • The accumulator versions hold: Loop.len at 100k, and Loop.split matches Base on empty / leading / trailing / adjacent separators and astral chars; 1.7 MB / 300k parts in ~170 ms.

    Bonus: your correction surfaced a live crash in our app. Our prompt-display path splits the full user text, so a pasted message of ~9k chars throws inside the artifact (we found it while re-checking your point — the same family, one frame chain deeper). We're now adopting the tail-recursive helpers in the affected core modules, not just the framing spec, and adding MB-scale regression tests.

    The native string_length / string_split entries in OPERATIONS would be very welcome on our side — happy to benchmark a patch or hand over the framing module as a test case, as offered.

    — confirmation run by the same agent (DeepSeek V4.1 Flash via OpenCode), at the request of the project owner.

  3. etafund commented on Sep 18, 2026

    @etafund

    Confirming on bend 2.0.5 (main @ e6676b0, Linux x86_64, node v24.19.0): the same per-character non-tail recursion also affects String.repeat (bend2/base.bend ~L1914). Executed today:

    str.bend:

    import Base
    
    def rep(s: String, n: Nat) -> String:
      String.repeat(s, n)
    

    str.mjs (run with node --import bend2/main.ts str.mjs):

    import B from "./str.bend";
    B.rep("ab", 15000n);   // 30,000-char output
    // → RangeError: Maximum call stack size exceeded (in the caller's process)

    One supporting contrast as a single data point: a 100,000-deep user-level recursion compiled to the C backend and ran in ~2 ms on the same machine, so the limit is specific to JS emission of non-tail calls (tail calls are trampolined and survive).

    Suggest making the Base String folds (length, repeat, split) tail-recursive with accumulators, plus a guide note on the JS non-tail recursion depth (host-stack dependent; ~10k frames in this environment).

  4. kreynolds commented on Sep 18, 2026

    @kreynolds
    Contributor

    The recursion is not specific to Base's string primitives. A hand-written
    recursion using no Base string functions at all fails identically, so
    rewriting String.length / String.split accumulator-style would hide this
    rather than fix it:

    import Base
    
    def mk(n: Nat, acc: String) -> String:
      match n:
        case 0n:
          acc
        case 1n+p:
          mk(p, SCon{'a', acc})
    
    def len(s: String) -> Nat:
      match s:
        case SNil{}:
          0n
        case SCon{h, t}:
          1n+len(t)
    
    def main() -> IO(Unit):
      do IO<Unit>:
        IO.print(Nat.show(len(mk(U32.to_nat(30000), SNil{}))))

    bend m.bend → bend: memory fault (machine stack overflow?)
    bend m.bend -o m && ./m → 30000

    Cause is in the emitter. js_call (comp.ts:2931-2932) emits a non-tail call
    as a nested host call:

    : tail ? "run_jump(" + js_sat(k) + ", [" + exprs.join(", ") + "])"
    : "run_loop(" + call + ")";

    so only tail calls are trampolined and the host stack grows one frame per
    level. Patching the emitted JS's catch in io_run to print the original
    error gives RangeError: Maximum call stack size exceeded with a stack of
    nothing but the recursive def. The C lane splits the same def at the cut,
    mints a continuation segment (FID_..._K8) and pushes the frame on STK;
    the JS lane has no equivalent.

    Two things that may be useful for triage:

    • The threshold is in frames, not bytes: 26552 ok / 26581 fails here, while a
      tail-recursive traversal of a 3,000,000-character string is fine. Total
      allocation is not the issue.
    • BUN_JSC_maxPerThreadStackUsage raises the ceiling but saturates around
      42k frames for every value tried (8 MB: 42023 ok / 42080 fail; 32 MB — the
      value gates/test.ts sets: 41367 / 43261; 1 GB: 41367 / 45156). 300000 still
      fails. So it is not a mitigation, which matters given the gates rely on it.

    Distinct from #779 / #791: those overflow in the checker while expanding a
    large unary Nat literal and report through main.ts. This one has no large
    literal, checks fine (the native build runs), and fails inside program code
    with the checker not loaded.

    bend 2.0.5, Darwin arm64, Homebrew clang 22.1.1.

    Found using Claude.

  5. VictorTaelin commented on Sep 18, 2026

    @VictorTaelin
    Contributor

    Partly addressed in 2.0.7: String.length is now a native intrinsic on the JS lane (counts code points directly), so it no longer recurses per character. The root cause, non-tail calls costing a host frame on the JS lane, is real and we WILL add continuation passing to the JS emitter; it is listed under SOON in WONTFIX.txt at the repo root, so please do not open further issues for other folds hitting the same depth limit until then. Thanks for the careful table.

    Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

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