Skip to content

A String match whose default arm uses the scrutinee takes memory and time quadratic in the keyword length #1266

Open

Description

@MavenRain

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)

  1. parse_patt expands a string pattern into a full bit-level pattern tree (bend.ts:1731-1733, lit_step at 1089-1094, word_to_term at 1064-1070). The tree is SCon, then Chr, then U32, then 32 WCon{True|False}, then WNil: 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.
  2. match_flatten (bend.ts:2634-2716) makes one Mat per constructor column. For the default row (a PVar), it substitutes the scrutinee with the rebuilt constructor kx = PCtr(c.k, fresh vars) through body_sub (bend.ts:2698-2700). body_sub wraps the body in a lazy Sub node (bend.ts:2609-2632).
  3. term_higher resolves each Sub with patt_term at each occurrence (bend.ts:717-719, 702-703, patt_term at 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).
  4. def.v = term_higher(term_lower(term_higher(body_flatten(...)))) (bend.ts:2484) keeps these copies. Check and Infer (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

  1. Lorenzobattistela commented on Oct 14, 2026

    @Lorenzobattistela
    Collaborator

    Reproduced on current main (dbb3157). We generated one kw(s) def that matches s against n string keywords, each L chars 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:

    n x L default arm peak RSS time JS size
    2 x 5 s 249 MiB 0.23s 20 KB
    8 x 5 "z" 131 MiB 0.15s 27 KB
    8 x 5 s 641 MiB 0.63s 40 KB
    8 x 10 "z" 211 MiB 0.25s 51 KB
    8 x 10 s 1970 MiB 1.96s 81 KB

    Main runs faster than the times you reported, but the growth looks the same. With the literal default, memory stays small. With s as 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's body_sub is 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.

  2. HamedShams commented on Oct 30, 2026

    @HamedShams
    Contributor

    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 matching s against n keywords of L characters, compiled to JS.

    n x L default arm peak RSS time
    2 x 5 s 279 MiB 0.31s
    2 x 5 "z" 103 MiB 0.13s
    8 x 5 s 731 MiB 0.86s
    8 x 5 "z" 134 MiB 0.18s
    8 x 10 s 2276 MiB 2.77s
    8 x 10 "z" 195 MiB 0.30s

    Where the memory goes, in match_flatten: a string pattern is expanded into its constructors before flattening (SCon, Chr, U32, then a WCon and a True/False for 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 with s replaced by the scrutinee rebuilt so far (body_sub(row.f, p0.i, x), then body_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 WCon chain of 32 known bits becomes a U32 literal, and SCon{Chr{c}, rest} with a literal rest becomes a String literal, 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 is lit_step in reverse, and u32_from_term and lit_of already 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 String without a copy. I'd leave that out unless you want it.

    @nicolas-abril, two questions before I start:

    1. Is folding into literals at materialisation the direction you'd take? The alternative is for the flattener to keep a literal pattern as one node that unfolds one layer per split, the way Lit does in the checker, so the rebuilt prefix is a literal by construction. Same result, but a bigger change to the flattener.
    2. fix(check): a constructor's fields grow as a list, without copying #1966 touches the match columns in the same function. I'd build on top of it and rebase once it lands, unless you'd rather I wait for it.

    For the test, the keyword match from the report as a .bend under tests/ 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.

  3. nicolas-abril commented on Nov 6, 2026

    @nicolas-abril
    Collaborator

    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_lower of the flattened body, the tree that def.v holds and that check and emit walk).

    The hub (src/server/main.bend, 386 files, 9.2 MB, 31.3k defs):

    • Loading alone allocates 43 GB (36 GB in term_higher) and keeps 1.56 GB live. Stored body nodes total 17.0M.
    • The top 100 defs hold 86% of them. 99 of those 100 have a string literal in a case pattern, and defs with one hold 89% of all stored nodes.
    • The worst, Hub.answer.k, is 9 lines and stores 1.43M nodes:
    match a:
      case M.Ask{_, +th, _, "settings_proposal", _, +options, True{}, _}:
        Settings.answer(String.eq(answer, "accept"), s, now, client, id, ask, answer, th, options)
      case M.Ask{_, +th, +k, +tool, _, _, True{}, _}:
        Hub.answer.cx.t(String.eq(tool, "checks_ok"), OR.Order.ask.is(tool), s, now, client, id, ask, answer, th, k)
      case M.Ask{_, _, _, _, _, _, False{}, _}:
        Step.outs([Reply.ok(client, id)])
    

    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:

    fallback body stored nodes
    2 17,261
    a call with 1 argument 24,203
    a call with 4 arguments 45,029
    a call with 10 arguments 86,681
    (34 characters, 10 arguments) 173,279

    It'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 the Bool): 734,010 stored nodes → 134.

    Whole hub with the 750 string literals in case patterns replaced by _. This drops the comparison, so it's a slightly optimistic stand-in for the String.eq rewrite. Check still passes:

    load check JS emit peak RSS
    main, as written 8.1 s 8.3 s out of memory (11 GB heap cap) —
    2.0.36, as written 8.1 s 7.3 s 60 s 8.0 GB
    main, literals → _ (Node) 1.0 s 0.8 s 3.4 s 2.6 GB
    main, literals → _ (Bun, BUN_JSC_forceRAMSize=4GiB as in their build) 1.0 s 1.1 s 3.7 s 4.5 GB

    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 Bool match on String.eq(x, lit), with a rewrite to recover x = lit in the hit branch. The core can't express it. A Mat applied 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 the Lit in the hit branch, no refinement in the miss branch, and a step rule that compares a Lit scrutinee by value and unfolds one layer against a built value.

    Meanwhile #2075 compiles String.eq to === on JS (1.92 s → 0.01 s for 2M comparisons of 17-character strings), so the String.eq workaround is also fast at runtime.

  4. HamedShams commented on Nov 7, 2026

    @HamedShams
    Contributor

    @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 Lit by 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_flatten last, with the keyword match from this report plus a nested-record case like Hub.answer.k as the tests.
    Let me know. In the meantime String.eq with #2075 covers people either way.

    The #1966 question is moot now, since the work moves out of the flattener!

  5. Simplereally commented on Nov 10, 2026

    @Simplereally

    AI Generated Comment

    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.eq lookups 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 error an arity over 247.

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