Skip to content

C emission expands an erased shared layout exponentially; depth 22 uses about 3 GiB #1270

Closed

Description

@jasisz

What I did

I passed a deeply nested Choice<...> only as the erased type argument of an identity function and emitted native C. No value of that type is constructed.

BEND_NO_TELEMETRY=1 bun bend2/main.ts erased_layout.bend --check-only
BEND_NO_TELEMETRY=1 bun bend2/main.ts erased_layout.bend -o erased_layout.mjs
BEND_NO_TELEMETRY=1 bun bend2/main.ts erased_layout.bend -o erased_layout.c
import Base

type Choice<-A: Data> is Data:
  Left{value: A}
  Right{value: A}

def id(-A: Data, x: U32) -> U32:
  x

def go(x: U32) -> IO(Unit):
  IO.print(U32.show(id(Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<Choice<U32>>>>>>>>>>>>>>>>>>>>>>, x)))

def main() -> IO(Unit):
  do IO<Unit>:
    x : U32 <- IO.thread_count()
    go(x)

What happened

On main commit 57b6c150f63704f53d533776deb3859578d4b09e, --check-only takes 0.46 s and JS emission takes 0.69 s, but C emission at depth 22 peaks at 3,063,728 KiB RSS. A harness that sampled the child with ps -o rss every 25 ms completed in 10.571 s. The emitted C is only about 78 KiB; it compiles normally, and JS and C both print 1.

Depth 20 already peaks at 789,552 KiB. Released v2.0.34 (7d8a3eb036042c6549461054d25a10f26d361c5c) peaks at 740,464 KiB at depth 20.

The head of PR #1244 (d4d27f3308c6c999d5aa3385d9a71040109a04e9) still peaks at 755,760 KiB at depth 20 and 2,985,200 KiB at depth 22. That PR fixes a separate JSON.stringify in the constructor cache.

Why

emit_native forms its specialization key with ers.map((e) => JSON.stringify(lay_of(fl.book, e))). Each Choice<A> layout points both arms at the same child layout, so the layout is a linear DAG, but JSON.stringify expands both references recursively. The key therefore has exponential size even though the source type and emitted program are linear in the nesting depth and the parameter is erased.

A layout-identity key, using the same stable memoized Lay objects without structural serialization, avoids expanding the DAG. This is the same underlying data shape as #1244 but a separate keying site that its patch does not touch.

Environment

Bend main 57b6c150f63704f53d533776deb3859578d4b09e
Bend v2.0.34 7d8a3eb036042c6549461054d25a10f26d361c5c
macOS arm64
Bun 1.4.2
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