Repository navigation
Description
What you did
bun bend2/main.ts main.bend -o out.js
main.bend is the file below. It matches a String against 8 keywords of 10 characters. The default arm returns the scrutinee.
What happened
The compile succeeds and the output is correct, but it uses 1.4 GB of memory and 20 s of CPU for a 460-byte file.
I measured each variant with one compile on bend2 at 57b6c150. "Peak RSS" is the maximum resident set of the process.
| Arms x keyword length | Default arm | Source | Peak RSS | CPU | out.js |
|---|---|---|---|---|---|
| 16 x 10 | case s: 0 |
687 B | 317 MiB | 5.2 s | 98 KB |
| 2 x 5 | case s: s |
246 B | 256 MiB | 3.3 s | 20 KB |
| 8 x 5 | case s: s |
414 B | 564 MiB | 8.1 s | 43 KB |
| 8 x 10 | case s: s |
460 B | 1,388 MiB | 20.2 s | 89 KB |
| 16 x 10 | case s: s |
725 B | 2,237 MiB | 44.8 s | 167 KB |
- The cost is linear in the number of arms and quadratic in the keyword length. At 8 arms, 5 to 10 characters gives about 4x.
- When the default arm does not use the scrutinee (
case s: 0), the cost is small and linear. - The emitted JS stays linear. The cost is in the checked term.
To find where the memory goes, I added a hook after book_valid and counted the nodes of the checked term of kw. These nodes have the form Ann(tm, Var("_", -1, ty)). I then deleted the checked terms and ran a full GC:
Arms x length (case s: s) |
Nodes in the checked kw |
Live heap after check |
|---|---|---|
| 8 x 5 | 238,578 | 143 MB |
| 8 x 10 | 926,298 | 515 MB |
| 16 x 10 | 1,852,290 | 1,020 MB |
Most of the nodes are WCon, False and True constructors, which are the bits of the characters of the scrutinee. v2.0.25 and v2.0.28 make 2x more nodes than 57b6c150 (16 x 10: 3,767,620).
This is not the conversion case in WONTFIX.txt ("the checker is not optimal"). No equality check is involved. The elaborated term is quadratic in the source before the checker compares anything.
A real program shows the same effect. In a 2,400-def book (1.5 MB of source), six such matches make 92% of the 2.96M checked nodes. That book holds 1.3 GB after check. Examples of the shape:
def Cli.Mapping.boolean(text):
match text:
case "true": IO.pure(Big, Big.one())
case "false": IO.pure(Big, Big.zero())
case _: Cli.Mapping.parse("expected true, false, ...", text)
Root cause (my reading of 57b6c150, not confirmed with a debugger)
parse_pattexpands a string pattern into a full bit-level pattern tree (bend.ts:1731-1733,lit_stepat 1089-1094,word_to_termat 1064-1070). The tree isSCon, thenChr, thenU32, then 32WCon{True|False}, thenWNil: about 66 constructors per character. The comment at bend.ts:94 says that this per-unit expansion is by design. It is linear and is not the problem.match_flatten(bend.ts:2634-2716) makes oneMatper constructor column. For the default row (aPVar), it substitutes the scrutinee with the rebuilt constructorkx = PCtr(c.k, fresh vars)throughbody_sub(bend.ts:2698-2700).body_subwraps the body in a lazySubnode (bend.ts:2609-2632).term_higherresolves eachSubwithpatt_termat each occurrence (bend.ts:717-719, 702-703,patt_termat 2722-2732). Each mismatch leaf gets a new copy of the whole prefix matched so far. A keyword of L characters has about 32 L mismatch leaves, and the prefix at a leaf has O(position) nodes. Thus each keyword costs O(L^2).def.v = term_higher(term_lower(term_higher(body_flatten(...))))(bend.ts:2484) keeps these copies.CheckandInfer(bend.ts:478-484) then put one annotation on each node.
Possible direction
Make each mismatch leaf share the rebuilt prefix, or bind the matched value one time, so the default arm costs O(L) per keyword. Keep the type refinement of the default arm and the usage counts of the binder unchanged. I did not write a patch because AGENTS.md says that bend.ts is human-written.
Workaround for users: in a string-literal match, do not use the scrutinee in the default arm. For example, compare with an equality chain.
The file
import Base
law kw:
for s: String
String
def kw(s):
match s:
case "aaaaaaaaaa":
"k"
case "baaaaaaaaa":
"k"
case "caaaaaaaaa":
"k"
case "daaaaaaaaa":
"k"
case "eaaaaaaaaa":
"k"
case "faaaaaaaaa":
"k"
case "gaaaaaaaaa":
"k"
case "haaaaaaaaa":
"k"
case s:
s
law main:
String
def main(): kw("haaaaaaaaa")
#|"k"
To make the other rows of the table, add arms or make the keywords longer. To make the control row, change case s: s to case s: 0.
bend --version
bend2 from source at 57b6c150 (main, 2026-10-02), run with bun 1.3.11. v2.0.25 and v2.0.28 also show this.
uname -sm
Darwin arm64
clang --version (the first line)
Apple clang version 21.0.0 (clang-2100.0.123.102)
Activity
Lorenzobattistela commentedon Oct 14, 2026
Reproduced on current main (dbb3157). We generated one
kw(s)def that matchessagainstnstring keywords, eachLchars long. The default arm is either the scrutinee (case s: s) or a literal (case s: "z"). We compiled each to JS and recorded peak RSS and time:s"z"s"z"sMain runs faster than the times you reported, but the growth looks the same. With the literal default, memory stays small. With
sas the default, doubling the keyword length (8x5 to 8x10) uses about 3x the memory and time. We stopped at 8x10 to keep memory down.We agree with your diagnosis:
match_flatten'sbody_subis expanded again at every mismatch leaf, so a default arm that uses the scrutinee gets rebuilt once per character of every keyword. We are leaving this open for a fix in the parser. Until then, the workaround is to avoid the scrutinee in the default arm.HamedShams commentedon Oct 30, 2026
I'd like to take this one, if nobody has started on it.
Re-measured on current main (9e8d7b7) with the setup above: one
kw(s)def matchingsagainst n keywords of L characters, compiled to JS.s"z"s"z"s"z"Where the memory goes, in
match_flatten: a string pattern is expanded into its constructors before flattening (SCon,Chr,U32, then aWConand aTrue/Falsefor each of the 32 bits), so a 10-character keyword is about 700 nested splits. At every split the default row is cloned into the constructor branch withsreplaced by the scrutinee rebuilt so far (body_sub(row.f, p0.i, x), thenbody_sub(g, x.i, kx)), and every split also has a mismatch leaf where that clone is materialised. A leaf at depth d holds a d-node rebuild, so the total is the sum of the depths: quadratic in the keyword length, with the bit expansion squared as the constant. That is why the literal default stays flat: nothing is rebuilt for it.What I'd do: fold the rebuilt scrutinee back into literals as it closes. A
WConchain of 32 known bits becomes aU32literal, andSCon{Chr{c}, rest}with a literalrestbecomes aStringliteral, so a leaf holds one literal node per matched character plus the bits of the character in progress, instead of ~70 nodes per character. That islit_stepin reverse, andu32_from_termandlit_ofalready do both halves. On paper it is still quadratic in L, but the constant drops by the expansion factor, which is where the 2 GiB is. I'd expect the 8 x 10 case to land in the tens of MiB, and the literal-default cases to be unchanged.Making it truly linear would need the default arm to receive the value without rebuilding it, so the scrutinee would be used twice (matched and returned), which affinity does not allow for a
Stringwithout a copy. I'd leave that out unless you want it.@nicolas-abril, two questions before I start:
Litdoes in the checker, so the rebuilt prefix is a literal by construction. Same result, but a bigger change to the flattener.For the test, the keyword match from the report as a
.bendundertests/with its expected output, so the shape stays covered; the memory numbers go in the PR.@Lorenzobattistela, thanks for the measurements above, I reused your setup.
nicolas-abril commentedon Nov 6, 2026
Measurements from a real application, from looking into #2038. Backplane (BackplaneWorks/Backplane, public, pinned to 2.0.36) hits this at scale, and in a second shape: the default rows don't need to use the scrutinee. Their bodies are copied at every split.
Setup: current main (
e75ccac0), macOS, Node 26 / Bun 1.3.14, single runs. "Stored nodes" counts the nodes of each def's body after loading (term_lowerof the flattened body, the tree thatdef.vholds and that check and emit walk).The hub (
src/server/main.bend, 386 files, 9.2 MB, 31.3k defs):term_higher) and keeps 1.56 GB live. Stored body nodes total 17.0M.casepattern, and defs with one hold 89% of all stored nodes.Hub.answer.k, is 9 lines and stores 1.43M nodes:Isolated. A 17-character literal nested in a record pattern, with two other arms whose bodies don't mention the scrutinee. Stored nodes against the fallback body's size:
2It's linear in literal length × fallback size: every bit-level failure point gets its own copy of the other rows, about 400 copies for 17 characters. Folding the rebuilt scrutinee back into literals wouldn't change these numbers, since nothing here rebuilds the scrutinee. Only the second option above, a literal pattern kept as one node, covers both shapes.
Same logic written with
String.eq(a helper def matching theBool): 734,010 stored nodes → 134.Whole hub with the 750 string literals in
casepatterns replaced by_. This drops the comparison, so it's a slightly optimistic stand-in for theString.eqrewrite. Check still passes:_(Node)_(Bun,BUN_JSC_forceRAMSize=4GiBas in their build)Stored nodes go from 17.0M to 2.0M. The emit OOM on main bisects to 3ed8746 (#1817): without string patterns, main beats 2.0.36 (2.6 vs 4.4 GB), so that regression only shows on these bit trees.
On the fix. I tried a flattener-only version: split a literal column as a
Boolmatch onString.eq(x, lit), with a rewrite to recoverx = litin the hit branch. The core can't express it. AMatapplied to a computed value is the banned lambda-match application (33c2d27), and the rewrite's motive is the goal, which doesn't exist at parse time. So a literal kept as one node needs a checker rule too: refine to theLitin the hit branch, no refinement in the miss branch, and a step rule that compares aLitscrutinee by value and unfolds one layer against a built value.Meanwhile #2075 compiles
String.eqto===on JS (1.92 s → 0.01 s for 2M comparisons of 17-character strings), so theString.eqworkaround is also fast at runtime.HamedShams commentedon Nov 7, 2026
@nicolas-abril Thanks, the Backplane numbers settles it.
The second shape – where the other rows get copied at every bit-level split even when nothing rebuilds the scrutinee – is the one that matters at scale, and folding the rebuilt scrutinee back into a literal does nothing for it. So I'm dropping that idea.
That leaves the literal kept as one node and from your write-up that's no longer a flattener change: it needs the checker rule for the hit and miss branches and the step rule that compares a
Litby value and unfolds one layer at a time. You are further into this than I am - since you've already tried the flattener-only version and hit the core limit.Given that, it probably make more sense for you to finish it. Or if you'd rather hand it over, I'm still happy to do it on the spec in your comment: checker and step rules first,
match_flattenlast, with the keyword match from this report plus a nested-record case likeHub.answer.kas the tests.Let me know. In the meantime
String.eqwith #2075 covers people either way.The #1966 question is moot now, since the work moves out of the flattener!
Simplereally commentedon Nov 10, 2026
Confirmed on Bend 2.0.40's C target on macOS. One dispatch matched 35 action keys, such as
"person.create", and its wildcard arm returned an unknown-command error without reading the scrutinee.An instrumented build reached 2,317 MiB of process-group physical footprint and was stopped by a 2 GiB guard during C emission, before any C file was written. Replacing the command, route, and status string patterns with
String.eqlookups followed by constructor matches let stock 2.0.40 reach C header generation in 4.91 s at 1,367 MiB peak physical footprint, where it stopped with the separate erroran arity over 247.