Skip to content

Emission exhausts the host stack on a finite 4096-let chain (reproduced in 2.0.36, 2.0.39 and 2.0.40) #2093

Closed as not planned

Description

@IlyaGulya

Summary

On official Bend 2.0.36, 2.0.39 and 2.0.40, the identical Base-only program generated below passes --check-only, but both native compilation and JS emission exit 1 with:

Error: the machine stack overflowed (a deep recursion, or a literal too large to expand)

The program has 4096 sequential U32.add bindings and takes its initial value from IO.args. It has no recursive type alias, large Nat/string literal, application imports, or host FFI. The largest numeric literal in the generated Bend source is 1.

Reproducer

Save the following as gen.py, then run python3 gen.py:

from pathlib import Path

n = 4096
source = """import Base

def number(m: Maybe<&2, U32>) -> U32:
  match m:
    case Some{n}: n
    case None{}: 0

def input(args: List<String>) -> U32:
  match args:
    case Nil{}: 0
    case path <> tail:
      match tail:
        case Nil{}: 0
        case value <> rest: number(U32.read(value))
"""
source += "\ndef work(x: U32) -> U32:\n"
previous = "x"
for i in range(n):
    source += f"  v{i} = U32.add({previous}, 1)\n"
    previous = f"v{i}"
source += f"  {previous}\n"
source += """
def main() -> IO(Unit):
  do IO<Unit>:
    args : List<String> <- IO.args()
    result : U32 = work(input(args))
    IO.print(U32.show(result))
"""
Path("deep.bend").write_text(source)

The generated file is 112,930 bytes, SHA-256 a743afea20b6b3a0512f6f86f621fe7fb1e261f97823a94d17a4669c38baf702.

bend version
# bend 2.0.40

bend deep.bend --check-only
# ALL PROOFS CHECK
# Use --verdict for mathematical validity.
# exit 0

bend deep.bend -o deep.native
# Error: the machine stack overflowed (a deep recursion, or a literal too large to expand)
# exit 1

bend deep.bend -o deep.js
# Error: the machine stack overflowed (a deep recursion, or a literal too large to expand)
# exit 1

The check-only output establishes typed compatibility, not mathematical validity.

Official release Typed check Native emission JS emission
2.0.36 exit 0, ALL PROOFS CHECK exit 1, stack exhaustion exit 1, stack exhaustion
2.0.39 exit 0, ALL PROOFS CHECK exit 1, stack exhaustion exit 1, stack exhaustion
2.0.40 exit 0, ALL PROOFS CHECK exit 1, stack exhaustion exit 1, stack exhaustion

The 2.0.36 and 2.0.39 rows are fresh controlled runs on the byte-identical source, same host, same selected CC, and unchanged OS/VM stack budgets. The 2.0.40 row reuses the previously recorded identical-source/binary observation; it was not rerun merely to reconfirm failure.

This reproducer does not establish a newly introduced 2.0.40 regression. It also does not compare the maximum passing depth across versions. A smaller 768-binding native compilation completed on 2.0.40; I have not established the smallest failing length.

Narrowed cause

Using the tagged 2.0.40 sources at 624dd9f4607cd29b0871a9b96d413bfb11e92f52 with external Bun 1.4.4 and diagnostic-only original exception reporting, C emission fails with RangeError: Maximum call stack size exceeded.

The expanded stack shows nested use analysis:

term_uses -> term_kids -> let_live -> rest_use -> term_uses -> ...

The immediate top of that standalone trace is term_higher, reached by term_open; the enclosing use/liveness calls account for the repeated depth. On a larger real application, the trace directly repeats the term_uses child-reduction frames at comp.ts:538.

This source diagnostic used an external Bun, not an assertion that it is identical to the official binary's embedded runtime. No compiler stack-budget override was used for the failing source or official-binary reproductions. Increasing the number of captured stack frames was diagnostic-only, not an increase in the VM stack budget.

Focused repair experiment

An experimental iterative use-analysis change eliminates this failure. The repaired source compiler builds the reproducer; its native and emitted-JS programs both print 4103 for argument 7.

After compiling with that experimental repair:

./deep.native +RTS --threads 1 -RTS --RTS 7
# 4103
bun deep.js 7
# 4103

On the real application, the repaired compiler at ordinary resources emits C byte-identical to the unmodified source compiler with an explicitly enlarged stack budget. The resulting native application also passes focused execution/reuse/corruption controls. Small ownership, let-liveness, closure-capture and match controls retain their original C and native/JS outputs; an invalid Bool body for an IO(Unit) main is still rejected.

I am minimizing the compiler-only patch before proposing it. This is not a claim that every recursive compiler helper becomes stack-safe, and the installed official release has not been patched.

The reduced prototype changes only comp.ts (+36/-8 lines), but it currently measures 66,246 tokens using the gate's gpt-3.5-turbo counting model, against the permanent 66,000 cap. This is not a ready-to-merge PR, and I am not requesting a cap increase.

Relation to existing decisions

I read the closure discussions, not only the issue titles:

  • #791 already mentions approximately 4000 sequential do-block statements failing. Its maintainer closure identifies the Nat-checking case as a duplicate of Type checking a large Nat literal overflows the host stack without identifying the literal #779; #779's final note fixes Nat literals while retaining the general depth limitation. I am not claiming the first report of long-body stack exhaustion.
  • #1127 was closed by its reporter citing the WONTFIX policy for emitter recursion on a large expanded literal; I do not treat that as a separate maintainer decision on this use-analysis patch.
  • #993 explains the deliberate common-path tradeoff for exponential equality checking.

I understand those limits and am not requesting a beta-optimal checker or unlimited term depth. The standalone failure is already present in all three tested releases. Source-level diagnosis on 2.0.40 isolates the use-analysis traversal on ordinary sequential bindings, including a real-application failure without a giant literal; no old-release throw-site identity is claimed.

Is this specific term_uses/Let-liveness case already tracked, and would a focused iterative repair be welcome if it preserves emitted output and fits the existing source-size cap? Or is this case also intentionally covered by the existing WONTFIX policy?

Environment

  • Official Bend 2.0.36, 2.0.39 and 2.0.40 distributions; source-level diagnosis and repair are specifically against 2.0.40 tag commit 624dd9f4607cd29b0871a9b96d413bfb11e92f52.
  • macOS 26.6.2, Darwin arm64.
  • Compiler OS/VM stack budgets were not increased for the reproductions or patched-source passes.
  • Source diagnostics and source-fork checks: external Bun 1.4.4. Official embedded-runtime equivalence was not established.
  • Diagnosis, reproducer, patch and focused checks were prepared with AI assistance; the commands above are reproducible independently.

Activity

  1. IlyaGulya commented on Nov 8, 2026

    @IlyaGulya
    Author

    Update: we unblocked the real application on unmodified official Bend 2.0.40, without increasing OS/VM stack budgets.

    The failing emission unit was DynamicWorld:header: just six long, common-prefix string patterns. Replacing the patterns with exact String.eq comparisons avoided the problematic shape. The small Bool-parameter helpers preserve short-circuit evaluation and satisfy Bend's restriction against matching a computed scrutinee.

    Native and JS parser/load checks matched the original implementation (the reference was built with the experimental compiler). Real native execution, reuse, dependency switching, and corrupted-trace rejection also passed. Accepted strings and rejection behavior remain unchanged.

    This is an application-side workaround, not a compiler repair. It does not fix the standalone 4096-binding reproducer, but a private compiler fork is no longer needed for this application path.

    Complete application-side patch — one file, net +26 lines
    diff --git a/DynamicWorld.bend b/DynamicWorld.bend
    index 53e3cea..daaab2b 100644
    --- a/DynamicWorld.bend
    +++ b/DynamicWorld.bend
    @@ -42,15 +42,41 @@ def text(+path: String) -> IO(String):
     type Header is Data:
       Header{optional: Bool, selector: String}
     
    +# Exact value comparisons keep long common-prefix strings out of the pattern
    +# compiler's decision matrix. Helpers branch before the next comparison so
    +# strict argument evaluation does not compare later alternatives after a hit.
    +def header_unavailable_present(+hit: Bool) -> IO(Header):
    +  match hit:
    +    case True{}: IO.pure(Header, Header{True{}, "unavailable"})
    +    case False{}: abort(Header, "Unknown", "unsupported-or-incomplete-world-manifest")
    +
    +def header_unavailable_absent(+s: String, +hit: Bool) -> IO(Header):
    +  match hit:
    +    case True{}: IO.pure(Header, Header{False{}, "unavailable"})
    +    case False{}: header_unavailable_present(String.eq(s, "world-v1\noptional=present\nselector=unavailable\n"))
    +
    +def header_modules_present(+s: String, +hit: Bool) -> IO(Header):
    +  match hit:
    +    case True{}: IO.pure(Header, Header{True{}, "modules-v1"})
    +    case False{}: header_unavailable_absent(s, String.eq(s, "world-v1\noptional=absent\nselector=unavailable\n"))
    +
    +def header_modules_absent(+s: String, +hit: Bool) -> IO(Header):
    +  match hit:
    +    case True{}: IO.pure(Header, Header{False{}, "modules-v1"})
    +    case False{}: header_modules_present(s, String.eq(s, "world-v1\noptional=present\nselector=modules-v1\n"))
    +
    +def header_kv_present(+s: String, +hit: Bool) -> IO(Header):
    +  match hit:
    +    case True{}: IO.pure(Header, Header{True{}, "kv-v1"})
    +    case False{}: header_modules_absent(s, String.eq(s, "world-v1\noptional=absent\nselector=modules-v1\n"))
    +
    +def header_kv_absent(+s: String, +hit: Bool) -> IO(Header):
    +  match hit:
    +    case True{}: IO.pure(Header, Header{False{}, "kv-v1"})
    +    case False{}: header_kv_present(s, String.eq(s, "world-v1\noptional=present\nselector=kv-v1\n"))
    +
     def header(+s: String) -> IO(Header):
    -  match s:
    -    case "world-v1\noptional=absent\nselector=kv-v1\n": IO.pure(Header, Header{False{}, "kv-v1"})
    -    case "world-v1\noptional=present\nselector=kv-v1\n": IO.pure(Header, Header{True{}, "kv-v1"})
    -    case "world-v1\noptional=absent\nselector=modules-v1\n": IO.pure(Header, Header{False{}, "modules-v1"})
    -    case "world-v1\noptional=present\nselector=modules-v1\n": IO.pure(Header, Header{True{}, "modules-v1"})
    -    case "world-v1\noptional=absent\nselector=unavailable\n": IO.pure(Header, Header{False{}, "unavailable"})
    -    case "world-v1\noptional=present\nselector=unavailable\n": IO.pure(Header, Header{True{}, "unavailable"})
    -    case _: abort(Header, "Unknown", "unsupported-or-incomplete-world-manifest")
    +  header_kv_absent(s, String.eq(s, "world-v1\noptional=absent\nselector=kv-v1\n"))
     
     def Header.optional(+h: Header) -> Bool:
       match h:
  2. YidaWeng commented on Nov 9, 2026

    @YidaWeng
    Contributor

    Two data points for the decision, on current main (f0ddfe7b, Bun 1.4.4, macOS 27.2, Apple M2 Pro, default 8 MB stack):

    • The reproducer still behaves as reported: --check-only passes, while -o deep.native and -o deep.js both exit 1 with the machine stack overflowed at 4,096 bindings.
    • The failing size is around 2,680 bindings on this host: 2,560 compiles and emits (three runs), 2,680 fails (three runs), and 2,672–2,678 is flaky. That edge is the stack layout moving under a fixed limit, not the source.

    On the cap: bend2/comp.ts is 65,974 ttok today against 66,000, so the prototype's 66,246 on 2.0.40 (65,977) is +269 and lands at about 66,243 on current main, ~243 over. #2088 is the recent precedent for making room (65,994 → 65,940), and the caps are Taelin's call.

    The open questions are still the maintainers': is a focused iterative term_uses/let-liveness repair wanted at all, and if so must it be net-neutral in comp.ts (paired with an offsetting simplification), or is a small cap increase acceptable? I can prototype the iterative form and report its exact ttok delta and reproducer output if that helps the decision.

  3. nicolas-abril commented on Nov 17, 2026

    @nicolas-abril
    Collaborator

    Closing as not worth fixing: 4096 sequential lets in one def is far beyond hand-written code. Split the work across defs. At realistic sizes the cost can't be measured, and each fix adds code to bend.ts, which has a size cap.

  4. paymog commented on Nov 22, 2026

    @paymog

    Application workaround data point: bend-kit HTTP acceptance previously reported the native host-stack diagnostic on official Bend 2.0.40 on arm64 macOS. Its combined check also later exceeded a 20 GiB memory cap. Keeping the same test helpers and splitting the reachable entrypoints into local socket checks, mTLS checks, and HTTP/2 pool/stream checks lets the complete native harness pass with default host-stack settings (94.7 seconds total, 9318 MiB peak process-tree RSS). HTTP/2 connection reuse and RST_STREAM(CANCEL) assertions still pass. This is only an application-side workaround, not a compiler repair or a new minimal reproducer. The existing standalone reproduction here is sufficient for the upstream limit.

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