Repository navigation
Description
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, formatesm, no minify
Possible directions
- Emit
String.split/String.lengthas loops, or move the recursive call into tail position under the existingrun_loop/run_jumptrampoline. - Or use native JS operations where semantics match (splitting on a char,
.length) — the wayString.takealready appears to. - If the recursion is intentional, documenting the input-size limit would help. Related but distinct: Type checking a large Nat literal overflows the host stack without identifying the literal #779 / Checker recursion depth: valid programs with ~10k-deep terms (e.g. a 10000n literal) fail with "machine stack overflowed" #791 are about check-time depth; this is runtime.
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
aron-intframe commentedon Sep 18, 2026
Reproduced on current main (0b7e2b1,
VERSION = "2.0.5"), compiling through the loader inbend2/main.tsand running the emitted JS under Node 20.20 and Bun 1.4.2. Same numbers as yours:String.splitandString.lengththrowRangeErrorat 10k chars on Node and at 20k/100k on Bun.Two things to add.
1.
String.takeis not special, and it is not native. Inbase.bendit has the exact same shape assplit/length(SCon{h, String.take(t, p)}, non-tail), and the emitter has no intrinsic for it. It only looked fine because your test callsString.take(s, 5n): recursion depth isn, not the string length. Calling it withn= string length overflows at the same sizes:Same family at 100k chars on Node:
String.to_upperandString.to_listthrow as well.String.reverse,String.drop,String.trimare fine because their self-call is already in tail position (they go throughrun_jump).String.appendis fine becausecomp.tsmaps 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_jumpand the trampoline keeps the stack flat. Mutual recursion is not allowed andmatchcannot scrutinize a computed value, so the per-char decision goes into a non-recursive step helper that returns the new state as a tuple:Checks clean. Output matches
String.splitfrom Base on the edge cases I tried (empty string, leading/trailing/adjacent separators, astral chars), and it handles your 11 MB case:Emitted JS for the loop version, for comparison with the one in your report:
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_liston the JS lane without touching the emitter; astring_length/string_splitentry next tostring_appendinOPERATIONSwould be the faster route for the two hot ones.FariaDev commentedon Sep 18, 2026
Thanks @aron-intframe — confirmed on our side, and the
takecorrection was spot on: our own probe had the same blind spot (smalln), 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)→RangeErrorat 10k;String.length→RangeErrorat 10k;String.to_upper/String.to_list→RangeErrorat 100k.Loop.lenat 100k, andLoop.splitmatches 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_splitentries inOPERATIONSwould 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.
etafund commentedon Sep 18, 2026
Confirming on bend 2.0.5 (
main@ e6676b0, Linux x86_64, node v24.19.0): the same per-character non-tail recursion also affectsString.repeat(bend2/base.bend~L1914). Executed today:str.bend:str.mjs(run withnode --import bend2/main.ts str.mjs):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).kreynolds commentedon Sep 18, 2026
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.splitaccumulator-style would hide thisrather than fix it:
bend m.bend→bend: memory fault (machine stack overflow?)bend m.bend -o m && ./m→30000Cause is in the emitter.
js_call(comp.ts:2931-2932) emits a non-tail callas a nested host call:
so only tail calls are trampolined and the host stack grows one frame per
level. Patching the emitted JS's
catchinio_runto print the originalerror gives
RangeError: Maximum call stack size exceededwith a stack ofnothing but the recursive def. The C lane splits the same def at the cut,
mints a continuation segment (
FID_..._K8) and pushes the frame onSTK;the JS lane has no equivalent.
Two things that may be useful for triage:
tail-recursive traversal of a 3,000,000-character string is fine. Total
allocation is not the issue.
BUN_JSC_maxPerThreadStackUsageraises the ceiling but saturates around42k 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
Natliteral and report through main.ts. This one has no largeliteral, 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.
VictorTaelin commentedon Sep 18, 2026
Partly addressed in 2.0.7:
String.lengthis 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.
UPSTREAM U20: the JS lane recurses on the host stack (found by tests/…