Skip to content

[JSC] YARR: add a non-backtracking matcher behind useRegExpLinearEngine - #750

Draft
robobun wants to merge 1 commit into
mainfrom
robobun/96d7caac/yarr-linear-engine
Draft

robobun wants to merge 1 commit into
mainfrom
robobun/96d7caac/yarr-linear-engine

Conversation

@robobun

@robobun robobun commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

For oven-sh/bun#44384, requested by @alii.

On hold. #777 (useMemoizedRegExp) bounds the same searches in the existing engines at the JIT's speed. I suggest #777 as the switch, and this matcher at most as a fallback for what #777 does not memoize.

Problem

  • YARR matches by backtracking: /(a*)*b/ on 28 a plus ! takes 0.7 s.
  • At its limits it answers "no match": /(a*)*b|a*!/.test("a".repeat(64) + "!") is false (Yarr.h:62).

Fix

  • useRegExpLinearEngine (default false): RegExp::compile asks a compiler (yarr/YarrLinear.cpp) for an automaton program, and Yarr::interpret runs it.
  • It bounds steps per position and working memory. A refused pattern runs as without the option.
  • Verified: JSTests/stress/regexp-linear-engine-*.js (step counts, no clock), JSTests/regexpLinearEngine.yaml, Tools/yarr-fuzz.
  • Self-reviewed: 58 concerns raised, 55 addressed. Not done: a hasCodeFor arm, a total-work limit, the optimizeBOL fix.

Background

Downsides

  • Option on: an accepted pattern takes 10 to 94 times the JIT's time per hot test() (3,418 times with a {1,500} group). [YARR] Match memoization, behind useMemoizedRegExp (off by default) #777: 0.9 to 1.2 times, one pattern 2.5.
  • Option off: +74,720 bytes of text (lto jsc), 1 to 9 more instructions per bytecode-interpreter match, no diff on the JIT path.
  • A refused pattern has no bound (policy open). Its first use costs up to 9% more, or 3 ms when too large.
Notes

Relation to #777 (added 16 October)

#777 (useMemoizedRegExp, default off, opened on 8 October, after this PR) bounds backtracking inside the existing engines. The JIT keeps a budget and hands a match that passes it to the interpreter. The interpreter then remembers the (cache point, position) pairs that failed, and does not try them again. I ran the lto jsc that CI built for each PR (linux x64, this head and f45f06f) on the same cases.

The first call of a hostile search, in ms. Every engine answers "no match", which is correct, except in the second row. There the subject matches, both options say so, and the engines without an option say "no match".

pattern subject option off this PR #777
/(a*)*b/ 28 a and ! 696 0.07 0.13
/(a*)*b|a*!/ 64 a and ! 676, and a wrong "no match" 0.05 0.15
/a*a*a*a*a*a*a*a*b/ 48 a 3,997 0.03 0.10
/\s+$/ 60,000 spaces and x 1,693 2.1 7.6
an e-mail validator with (...)* around (...)+ 30 a and ! 409 0.08 0.29
/^(?=(a+)+b)/ 30 a 632 634 (refused) 0.15
/^(?=(?:.*\d)+x)(?=.*[a-z])\w{6,}/ 30 1 360 356 (refused) 0.15
/^(?:\w+\s?){1,500}$/ 28 a and ! 459 0.20 467 (not memoized)
/^(?:a*){1000}b/ 30 a 880 1.1 1,059 (not memoized)
/^(?:a|a){1,2000}$/ 40 a and ! 414 0.66 406 (not memoized)
/(?:\w+\s?){1,9000}!/ 12,000 a 462 2,257 455 (not memoized)
/(a*)*\1b/ 28 a and ! 721 712 (refused) 708 (not memoized)

A hot test() on a subject that matches, in ns per call (the fastest of four runs, the JavaScript tiers on, a quiet machine). Each option is measured against its own binary without the option.

pattern this PR, off on ratio #777, off on ratio
/\.json$/ 10.3 105 10.2 10.0 10.2 1.02
/\s+$/ 12.2 158 13.0 12.0 12.2 1.02
UUID, /i 27.3 534 19.6 27.6 26.7 0.97
/^.{1,255}$/ 10.2 366 35.9 10.5 9.9 0.94
/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/ 21.6 592 27.4 23.0 22.4 0.97
/(\d{4})-(\d{2})-(\d{2})/ 13.3 427 32.1 13.0 13.5 1.04
/^v?(\d+)\.(\d+)\.(\d+)(?:-([\w.]+))?$/ 13.8 405 29.3 13.4 15.3 1.14
/^\/users\/(\d+)\/posts\/(\d+)$/ 5.5 518 94.2 5.5 13.6 2.47
/^[A-Za-z0-9+\/]{4,4096}={0,2}$/ 1,593 85,952 54.0 1,563 1,573 1.01
/^.{1,10000}$/ 10.9 1,810 166 11.0 10.8 0.98
/^\p{RGI_Emoji}$/v 14.8 3,825 258 14.6 14.5 0.99
/^(?:\w+\s?){1,500}$/ 158 539,996 3,418 157 159 1.01
/<(\w+)>[^<]*<\/\1>/ 18.8 18.7 0.99 18.1 19.0 1.05
/(?=.*\d)(?=.*[a-z])\w{6,}/ 36.2 36.3 1.00 37.4 43.3 1.16

What the numbers say:

What I suggest:

  1. [YARR] Match memoization, behind useMemoizedRegExp (off by default) #777 is the switch. It puts the bound in the engines that backtrack, a hot match stays at the JIT's time, and there is no third engine to keep.
  2. This PR then ends in one of two ways. A maintainer decides which.
  3. Some parts here do not depend on that choice and can test [YARR] Match memoization, behind useMemoizedRegExp (off by default) #777: the pattern generator, the collection that runs the regexp stress tests under an option (JSTests/regexpLinearEngine.yaml), and the Tools/yarr-fuzz configurations.
  4. Add --experimental-linear-regexp: a non-backtracking matcher for the patterns that allow it bun#44384 follows this PR. When Bun has a WebKit with [YARR] Match memoization, behind useMemoizedRegExp (off by default) #777, BUN_JSC_useMemoizedRegExp=1 turns it on with no change in Bun. If a named flag is wanted, the plumbing of that PR can set useMemoizedRegExp.

Open decisions for a maintainer

These apply only if this matcher is kept (the section above).

  1. What a refused pattern does when the option is on. Each answer has a different size:
    • This PR: it runs as without the option, and --reportRegExpLinearRefusals=1 names it. V8's --default-to-experimental-regexp-engine does the same: on node v26.3.0 a backreference, a lookahead, /i and /u stay on its backtracking engine with no error.
    • An error. V8 raises one only for a RegExp that opted in with its l flag, and at construction ("Cannot be executed in linear time"). Here the ask is in RegExp::compile, so an error there (a new Yarr::ErrorCode) comes out of the first test() or exec(). An error at construction needs the ask in RegExp::finishCreation with the lazy construction of the pattern off, and an answer for a RegExp that comes from the bytecode cache. Yarr::RegularExpression has its own chooser and needs its own answer.
    • A step budget that throws. That is [JSC] A RegExp search that Yarr abandons throws a RangeError #343, plus counters at every backtrack point of the JIT and the interpreter: matchLimit counts only where a group is entered, so /a*a*a*a*a*a*a*a*b/ has no limit at all (13 s on 48 characters, and 0.09 ms on the matcher). Those counters run with the option off too.
  2. The caps. A program has at most maximumRegExpLinearProgramSize instructions (65,536), which allows 262,144 steps per position, and maximumRegExpLinearWorkingMemory bytes (8 MB). Lower caps refuse more patterns, so this decision depends on the first one. The caps also decide the most one search can cost, because the matcher has no limit on the total work of a search ("What the option does not bound" below).
  3. The cost of an accepted pattern. The matcher is the only engine of an accepted RegExp, and it is slow next to the JIT (table below). Two shapes keep the JIT for the common case. Neither is in this PR:
    • Keep the JIT for a pattern whose backtracking is bounded by its shape (no unbounded quantifier, and few ways through it). That needs a bound that also proves the match limit cannot be hit.
    • Keep the JIT for every pattern and move a match to this matcher when it passes a backtrack budget, as V8's --enable-experimental-regexp-engine-on-excessive-backtracks does. That needs the counters of decision 1.
  4. The upkeep, and who has it. This is a third RegExp engine, and only this fork has it: the existing files of yarr/ go from 0 to 14 USE(BUN_JSC_ADDITIONS) blocks, and YarrLinear.cpp is 1,700 lines. It reads YarrPattern, so a change of what the parser produces can need a change here. Upstream merges touched yarr/ 4 times in 46 days. What lowers the cost is in "Upkeep" below. What stays: the guards at compile time catch a new kind of term, and a change of meaning is caught only by tests, on two test lanes that the release does not wait for.

How it works

  • RegExp::compile and RegExp::compileMatchOnly call Yarr::byteCompileLinear before the JIT conditions. compileMatchOnly builds a pattern with every group for that, because exec shares what it compiles. It does not build one for a pattern with a backreference, which the matcher refuses first.
  • A RegExp asks once, and before the JIT. Yarr::jitCompile reorders the terms of the pattern it is given (optimizeAlternative), and the program takes the terms in order. The compiler also refuses a pattern whose terms are out of order, whoever asks with it (LinearRefusal::PatternReorderedForJIT).
  • A refusal is about the pattern and nothing else, so the same pattern is refused every time. It is kept on the RegExp (one byte, in padding), so that the other character size and the fallback to bytecode do not ask again.
  • The stack does not choose the engine. The compiler recurses once per level of groups, and refuses a pattern with more than 32 levels (the deepest of 9,489 literals from packages has 8). When the stack still has too little room, the compile fails with the error the other stages of a compile have (TooManyDisjunctions): the match throws a RangeError, nothing is remembered, and the next match asks again.
  • Yarr::RegularExpression has the interpreter and no other engine. It asks in its own compile. Yarr::byteCompile is the upstream function and does not ask.
  • DFG and FTL inline a RegExp only when it has JIT code, so an accepted RegExp is never inlined. The compiler thread matches it with the same program when it folds a node.
  • optimizeDotStarWrappedExpressions rewrites /^.*X.*$/ to X and a DotStarEnclosure term. The compiler of the matcher expands that term to the pattern as it was written, so YarrPattern.cpp has no diff and a refused pattern keeps the rewrite.
  • A pattern whose alternatives all have a fixed length and end with $ can only match at the end. The matcher starts that far from the end, as the other engines do, so /\.json$/ does not read the subject.
  • The empty-iteration rule of RepeatMatcher is one bit per state: "consumed since the iteration began". A state is the pair (instruction, bit).
  • Steps bound: at one position an instruction is visited at most twice, and an instruction that waits on a character has at most that many states. So the pattern's own code costs a position at most 4 steps per instruction. The code of a lookaround has no loop, so one pass finds the fewest and the most characters read before each instruction. A lookaround costs one evaluation per offset that asserts it.
  • Memory bound: two lists of states, each state with a copy of the capture slots, the visited table, and the frames of the depth-first walk (one per slot an instruction wrote). The compiler counts the states and the frames of each code, and the matcher lets no vector grow past those counts, so the bound does not depend on how a Vector grows. (a?) x 2,400 needed about 185 MB under the old limit (maxRegExpStackSize, 192 MB). It is now refused.
  • Accepted: the flags dgimsuvy, groups and named groups (also duplicated names), greedy and lazy quantifiers, counted repeats (unrolled), ^ $ \b \B, modifiers, class sets, and lookarounds whose body has a bounded length, with captures.
  • Refused, with the reason in LinearRefusal: a backreference, a lookaround of unbounded length, lookarounds more than 16 deep or too costly, groups more than 32 deep, a program over the size cap, working memory over its cap, a kind of term the compiler does not know.
  • verifyRegExpLinearEngine (default false, for tests): after each match of the matcher, the bytecode interpreter matches the same bytecode from the same start, and the process ends when the two do not agree on the match or on the groups. The bytecode of an accepted RegExp has the interpreter's body beside the program for this.
  • $vm.regExpMatchStatistics(regExp, string, start) returns { index, captures, engine, refusal, jit, gaveUp, linearCompiles, programSize, maximumStepsPerPosition, maximumScratchBytes, steps, scratchBytes } for the engine the RegExp is compiled for. linearCompiles counts the asks of every RegExp of the VM. With the mode "backtracking" the bytecode interpreter matches the same RegExp. With the mode "outOfStack" a RegExp that asks in that call finds the compiler out of stack.
  • $vm.regExpMatchOnBothEngines(regExp, string, start) matches on both and compares the output vectors. It returns the index of the match, false when the two differ, and null when the interpreter gave up. For these functions the interpreter has a match limit of 100,000 in place of 100,000,000 and reports when it gives up, so a test never compares with the "no match" of a limit, and never waits seconds for it.
  • $vm.regExpLinearRefusalAfterJITCompile(regExp) asks the matcher with a pattern the JIT has compiled, which no RegExp does.

Where the answer is not the backtracking engines' answer

  1. At a limit. A backtracking engine that reaches matchLimit, or fills its pool of contexts, answers "no match". The matcher has neither limit and answers what the subject has.
  2. Inside a surrogate pair, with u or v. The matcher takes no match between the two halves of a pair, which is not a position of the subject. A RegExp never takes one either: where a backtracking engine finds one, RegExp::matchInline searches again after the pair. Two places show a difference.
    • /.*X.*/: /.*\B.*/u.test("a\u{1F600}a") is true on the JIT and on the interpreter, and false on the matcher. The backtracking engines search for X alone (DotStarEnclosure) and find it between the halves. false is the answer of the specification. regexp-linear-engine-semantics.js pins this case and /.*(?<=\uD83D).*/u for the matcher only.
    • Yarr::RegularExpression has no search after the pair. With the option, /\B/v on "a\u{1F600}a" goes from a match at 2 to no match. No test runs that route with a pair.
  3. A ^ in a lookahead inside a lookbehind, when another alternative begins with ^: /(?<=(?=^|x)a)b|^2/.exec("ab") is null on the JIT and on the interpreter, and index 1 on the matcher and on V8. optimizeBOL drops that ^ from the copy of the pattern that the backtracking engines retry after the start. That is a bug of the backtracking engines without the option too, reported on its own. Its sibling /(?<=(?=^)a)b|^2/ is null on all three engines until that fix.

What the option does not bound

  • A refused pattern. It runs on the backtracking engines as before.
  • The total work of one search on an accepted pattern. The steps are linear in the subject, with a factor that the program decides: up to 262,144 steps per character at the default cap. /(?:\w+\s?){1,9000}!/ (63,003 instructions) on 12,000 a takes 5.2 s on the matcher. The JIT gives up at matchLimit after 1.0 s (its "no match" is the answer of the limit, and right here by chance). A lower maximumRegExpLinearProgramSize lowers this, and refuses more patterns (open decision 2). A limit on the steps of one search needs a way to report that the search was given up, which is what [JSC] A RegExp search that Yarr abandons throws a RangeError #343 adds.
  • A global loop (replace, matchAll, split). It runs one match per result. /a*b|a/g on n a characters takes about 3n² steps, as it does for a backtracking engine, and the matcher's steps are slower.

Relation to other open PRs

  • [YARR] Match memoization, behind useMemoizedRegExp (off by default) #777: the first section of these Notes.
  • [JSC] A RegExp search that Yarr abandons throws a RangeError #343 makes Yarr::interpret() and Interpreter::interpret() return JSRegExpResult. This PR adds the matcher's branch to interpret(), and test functions around it that take an unsigned from the interpreter. A merge of the two heads (8eade9e and this one) conflicts in yarr/YarrInterpreter.cpp, so the PR that lands second needs a rebase.
    • If [JSC] A RegExp search that Yarr abandons throws a RangeError #343 lands first, this PR changes about 25 lines in YarrInterpreter.cpp, YarrInterpreter.h and RegExp::matchForTesting: the matcher's branch returns Match or NoMatch, the test functions return JSRegExpResult, and "gave up" comes from isAbandoned() in place of the three flags this PR sets where the interpreter gives up. The tests and comments that say "no match at the limit" then say RangeError, and one run is added: a refused pattern with a low --regExpMatchLimit throws.
    • The collection of this PR already leaves out the tests whose run commands set --regExpMatchLimit or --maxRegExpStackSize. The seven tests that [JSC] A RegExp search that Yarr abandons throws a RangeError #343 adds all do, and the matcher has no such limit to reach.
  • [JSC] Ahead-of-time compilation #757 (draft) and WIP #743 (titled WIP) change the m_state != JITCode arm of hasCodeFor and hasMatchOnlyCodeFor to return m_workInInterpreter != workBeforeJIT;, so that a RegExp on bytecode is compiled again for the JIT after 256 units of work. An accepted RegExp stays on bytecode. After that merge it is compiled again for each match. regexp-linear-engine-compile-once.js fails then, and so does an ASSERT in RegExp::compileForLinearMatcher. The change is usesLinearMatcher() || in that arm. They also put a uint16_t in the padding of RegExp where this PR has one byte. RegExp.cpp now asserts that a RegExp is at most 80 bytes, so that a merge that moves every RegExp to the next size class does not compile.

Upkeep

  • A PatternTerm::Type that the compiler does not know is a refusal, so a new kind of term runs on the backtracking engines until the matcher has it.
  • -Wswitch is an error in YarrLinear.cpp, so a new enumerator in a type its switches name stops the build there.
  • JSTests/regexpLinearEngine.yaml is in the list of run-javascriptcore-tests. It runs the regexp tests of JSTests/stress once more with the option and with verifyRegExpLinearEngine: 428 runs, about one and a half minutes with 8 jobs. A test that comes with a change of YarrPattern runs there too, and a difference between the matcher and the interpreter ends the process, also in a test that only prints what it finds.
  • JSTests/BUN-TEST-DIFFERENCES.md (section E, step 4) says what to do with a test that fails only there: find the engine that is right first. Where the fix of the matcher is not plain, make the compiler refuse the construct.

Refused patterns in real code

A corpus of 9,809 RegExp literals from 539 packages (the packages in bun's test tree, and bun's src/js), classified with the build of an earlier head: 9,274 accepted, 535 refused (5.45%). 329 have a lookaround of unbounded length, 205 a backreference, 1 is too large. Outside syntax-highlighter packages it is 93 of 5,374 (1.73%). 65 packages have at least one refused literal. No literal has groups more than 8 deep, so the limit of 32 levels refuses none of them.

Measurements (lto jsc from CI, linux x64, 0c06faa against this head)

In the table, some instruction counts of the matcher are from the head before this one (e896397). The commit between the two changes only how the interpreter's entry is inlined. The ns columns are from a loaded machine. The table in "Relation to #777" has ns from a quiet one.

  • size: text 48,044,303 to 48,119,023 (+74,720), data +208. By section: .text +70,192, .rodata +4,288, .data.rel.ro +208. The 44 symbols named for the matcher and its test functions are 61,179 bytes. The test functions and the verification are 9 of them and 17,131 bytes. A BytecodePattern is 8 bytes larger (120 to 128). A RegExp is not (80), and RegExp.cpp asserts that.
  • Option off, instructions per test() call (qemu-x86_64 -one-insn-per-tb, the JavaScript tiers off, base to this head), for /\.json$/, the date, the UUID and the route pattern of the table below. With the RegExp JIT: 801 to 798, 885 to 876, 1,249 to 1,247, 894 to 881. With --useRegExpJIT=0: 1,257 to 1,264, 5,066 to 5,068, 3,426 to 3,427, 2,665 to 2,674. One cell measured twice on one binary differs by up to 1%. There is no diff in YarrJIT.cpp, YarrJIT.h, YarrPattern.cpp, dfg/, ftl/ or RegExpInlines.h.
  • These counts found a cost on an earlier head. With the option off, a match on the bytecode interpreter took 25 to 40 instructions more than on base: the test function that runs the interpreter is a second caller of Interpreter::interpret(), and the lto build no longer inlined that into Yarr::interpret(). It is ALWAYS_INLINE now, which is 2,160 of the bytes above.
  • Option on against off, per test() call. Instructions are counted as above and are exact. Nanoseconds are from a hot loop in a function of its own, with the JavaScript tiers on: the fastest of six runs, JIT and matcher in turn. The machine is shared, and one cell varies by up to 40% between runs (the two refused rows run the same code in both columns).
pattern subject program steps JIT, instructions matcher, instructions ratio JIT, ns matcher, ns ratio
/\.json$/ 31 chars 9 15 798 2,898 3.6 18.0 337 18.7
/\s+$/ 33 chars 8 57 857 4,191 4.9 23.8 448 18.8
UUID, /i 36 chars 41 78 1,247 11,265 9.0 60.9 939 15.4
/^.{1,255}$/ 20 chars 514 87 997 9,560 9.6 19.3 790 40.9
/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/ 30 chars 26 180 1,126 15,081 13.4 46.0 1,340 29.1
/(\d{4})-(\d{2})-(\d{2})/ 25 chars 19 94 876 10,393 11.9 27.7 761 27.5
/^v?(\d+)\.(\d+)\.(\d+)(?:-([\w.]+))?$/ 16 chars 36 103 922 9,237 10.0 40.8 840 20.6
/^\/users\/(\d+)\/posts\/(\d+)$/ 24 chars 31 100 881 10,084 11.4 15.9 1,133 71.3
/^[A-Za-z0-9+\/]{4,4096}={0,2}$/ 4096 chars 8,197 28,661 41,707 2,112,343 50.6 4,909 260,469 53.1
/^.{1,10000}$/ 20 chars 20,004 87 997 33,856 34.0 26.0 4,367 168
/^\p{RGI_Emoji}$/v 1 emoji 10,586 1,154 909 78,074 85.9 42.6 9,679 227
/^(?:\w+\s?){1,500}$/ 257 chars 3,504 168,895 5,114 12,838,216 2,510 487 1,257,896 2,583
refused: /<(\w+)>[^<]*<\/\1>/ 41 chars 978 977 (JIT) 1.0 48.5 30.9 (JIT) 0.6
refused: /(?=.*\d)(?=.*[a-z])\w{6,}/ 24 chars 1,561 1,552 (JIT) 1.0 119 76.5 (JIT) 0.6
  • The instruction counts have the cost of the call in both columns, because the interpreter tier makes the call. Optimized code inlines the JIT's match, so the ratio of the times is higher than the ratio of the instructions.
  • Where the time goes: every match makes a matcher and zero-fills a table of two entries per instruction, and every state has a copy of the capture slots. The last rows are programs of counted repeats: the backtracking engines take one way through /^(?:\w+\s?){1,500}$/ on a valid subject, and the matcher follows every copy of the group. On a hostile 29-character subject (28 a and !) that pattern costs the backtracking engines 0.5 s, and the matcher 0.2 ms.
  • The first use of a RegExp, in instructions, option off to option on. Each RegExp is new, and the use is test(), then exec().
    • Refused for a backreference (/(a)\1b/): 29,030 to 29,864, 28,862 to 29,243. A longer pattern with a backreference: 66,531 to 66,367, 65,586 to 65,991. The compiler sees the backreference before it reads a term.
    • Refused for a lookaround of unbounded length (/(?=.*\d)\w{6,}x/): 57,839 to 62,923, 57,901 to 59,112. test() builds a second pattern, with every group, to ask with.
    • Refused as too large (/^(?:\w+\s?){1,20000}x$/): 27,964 to 11,537,337, 30,121 to 11,532,286. The compiler fills a program up to the cap before it refuses: about 3 ms, once per RegExp.
    • Accepted (the date pattern): 52,587 to 35,579, 54,789 to 28,890. A program and bytecode take the place of JIT code.
    • One cell varies by a few hundred instructions between runs: the allocator's slow paths fall on different RegExps.

Tests (nine files in JSTests/stress, 18 runs: the files with a second header also run with --useRegExpJIT=0)

  • regexp-linear-engine-semantics.js: 228 cases on the matcher, on the JIT and with --useRegExpJIT=0, and 3 for the matcher only (the exceptions above). The expectations are what all three and V8 report. It starts with three RegExps against the option: with the option each asked the matcher once, and without it none did, whichever call compiled it first.
  • -steps.js: steps at n, 2n and 3n are collinear and under the bound, for exponential, polynomial and lookaround patterns. A pattern that is anchored at the end takes the same steps at every length. It also pins the global loop as quadratic.
  • -differential.js: the matcher against the bytecode interpreter, in one process, with $vm.regExpMatchOnBothEngines. 11,985 accepted patterns: 5,808 of the shape .*X.* (with and without ^, $ and each flag), 3,481 made from a fixed sequence of numbers (2,644 with a lookaround), 521 made with a name that alternatives share, and hand-written sources for case folding, surrogate pairs, groups in loops and in lookarounds, and duplicate names. 1,391,774 matches from every start offset have the same output vector on both engines (446,387 of them are a match). The interpreter gave up on 6. 7 s on a Release build with assertions.
  • -step-bound.js: 2,000 patterns from the same generator (resources/regexp-linear-engine-patterns.js): 1,483 accepted, 1,070 of them with lookarounds, 35 too costly. No match passes its step bound or its memory bound.
  • -refused.js: every refusal reason, that a refused pattern has the JIT's code and its usual result, and that the matcher refuses a pattern the JIT has compiled and reordered.
  • -working-memory.js, with the default limit and with 65,536 bytes: the largest accepted member of two families, found by search, and the next one refused. One family is (?:(a)|(a)|...)*b, whose lists fill up: no match holds more than its bound.
  • -stack.js: 32 levels of groups are accepted and 33 are refused, for five kinds of group. A compile that finds no stack throws a RangeError, and the next use runs on the matcher: with the mode "outOfStack", and for RegExps first used from the deepest frame of a recursion. One run lets JavaScript use the stack to its end, as a thread with a small stack does, and one also leaves native code 70,000 bytes there, where the compiler does run out.
  • -compile-once.js: after 2,000 calls on 8-bit and 16-bit subjects and one match that reads 20,000 characters, three RegExps have asked the matcher three times, one of them a refused one. After the code is deleted an accepted RegExp asks once more.
  • -tiers.js: test, exec, replace, split, search and match in functions the DFG compiles, with a subject the compiler folds and one it cannot. /(a*)*b|a*!/ on 64 a plus ! says which engine ran: a backtracking engine answers "no match".
  • LinearProgram::match asserts both bounds in a build with assertions, and regex-fuzz.js checks them in the linear configurations.
  • Mutants: 17 one-line changes of the matcher and of RegExp.cpp, each run against the 18 runs. Every one fails a run. JSTests/regexpLinearEngine.yaml was run on three of them: a start one character too late fails 14 of its 428 runs, and a case-insensitive group read from the pattern's flags fails 3 runs with the verification and 1 without it (two of upstream's tests only print their failures).
  • Tools/yarr-fuzz on the sources of this head, configurations jit, interp, linear-verify and linear-interp, 10 profiles x 40 seeds x 250 cases: 152,109 cases, no crash and no verification abort. 3 cases differ between the JIT and a matcher configuration. In all three the JIT reaches its limit after 10 to 44 s and answers "no match", and linear-triage.js finds no difference on a search that the interpreter finishes. 103 seeds ran into the time limit of a seed (jit 21, interp 34, linear-verify 20, linear-interp 28). In the matcher configurations every slow case but one is a refused pattern. The one accepted case takes 571 ms, and its first exec costs 42 to 54 ms on every engine (the classes of a /isv pattern).
  • oven-sh/bun with this matcher: build 123887 of Add --experimental-linear-regexp: a non-backtracking matcher for the patterns that allow it bun#44384, pinned to an earlier head of this PR (ec05001), passed all 181 jobs: Linux (glibc, musl, ASAN), macOS and Windows, x64 and arm64. Its tests run the matcher through --experimental-linear-regexp on every platform.
  • test262, the RegExp subset (2,647 files), on the sources of this head: every file has the same verdict without the option and with --useRegExpLinearEngine=1 --verifyRegExpLinearEngine=1 (2,645 pass, and the same 2 fail in both with "regular expression too large"). No verification abort.

Self-review

  • First round: 9 concerns raised, 9 addressed. The engine is chosen per RegExp and a refused pattern keeps the JIT (the first head turned the JIT off for the process). The DotStarEnclosure is expanded. The memory bound counts the frames and has its own cap. The tiers test. The statistics hook reports the engine exec uses. The semantics file runs on three engines. The global-loop wording and test. The bounds are asserted at run time and in the fuzzer. A refusal report exists outside $vm.
  • Second round: 16 concerns raised, 15 addressed. It found two bugs. Yarr::byteCompile asked the matcher a second time, after the JIT had reordered the pattern, and a RegExp could then get wrong answers. The memory bound assumed that a Vector grows by a quarter, and it grows by a half. The rest: the order with [JSC] A RegExp search that Yarr abandons throws a RangeError #343, the compile count, the regexp tests under the option, the refusal of an unknown term, the tests and the generators for duplicated names, the runs with the RegExp JIT off, and the exception inside a surrogate pair.
  • Third round: 22 concerns raised, 20 addressed. A refusal for the stack of one compile stayed after a compile that threw (RegExp::reset): the stack no longer chooses the engine at all. The matcher read the whole subject for /\.json$/. The rest: the refusal of a reordered pattern, the compile count off the RegExp cell and the assertion on its size, verifyRegExpLinearEngine and its use in the collection, the pin of "option off asks nothing", the run with a small stack, the tests that [JSC] A RegExp search that Yarr abandons throws a RangeError #343 adds left out of the collection, the rule for a test that fails only in the collection, the cross-platform run in bun's CI, and the text of this body (V8's three modes, the open decisions sized, the total work of a search, the first compile of a refused RegExp, the third exception).
  • Fourth round: 11 concerns raised, 11 addressed. They are one finding: [YARR] Match memoization, behind useMemoizedRegExp (off by default) #777 was opened while this PR was in review, it bounds the same searches at a lower cost, and this PR did not name it. The PR is on hold, the comparison is the first section of these Notes, and the choice is with the maintainers.
  • Not done, 1: an arm for the matcher ahead of m_state != JITCode in hasCodeFor and hasMatchOnlyCodeFor, so that the merge with [JSC] Ahead-of-time compilation #757 needs no change. It is one more compare on each match of every RegExp, with the option off too. The arm that [JSC] Ahead-of-time compilation #757 rewrites is on the slow side of that test, and the test and the ASSERT named above fail until the change is there.
  • Not done, 2: a limit on the total work of one search. It needs a way to say that a search was given up, which [JSC] A RegExp search that Yarr abandons throws a RangeError #343 adds. Until then the caps bound it (open decision 2).
  • Not done, 3: the optimizeBOL fix for the third exception. It is a bug of the backtracking engines without the option, so it is reported for a PR of its own. This PR pins what the matcher answers.

Follow-ups, not in this PR

  • A limit on the steps of one search, reported as [JSC] A RegExp search that Yarr abandons throws a RangeError #343 reports an abandoned search.
  • A per-RegExp opt-in (a flag like V8's l). The option is read in three places, and a flag is an || in each.
  • An unbounded lookaround with no group inside can be matched with one bit per position. That is most of the 329 refused literals of that kind.
  • A backreference to a group that can capture only a few strings can be expanded.
  • With the option off, an accepted pattern can be run again on the matcher when a backtracking engine reaches a limit. That repairs the wrong "no match" by default.
  • The bytecode of an accepted RegExp has the interpreter's body, which only the tests and verifyRegExpLinearEngine run. It can be built when one of them asks for it.
  • A counted repeat can be refused from the size of its first copy. Today a pattern that is too large fills a program up to the cap before it is refused.

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Preview build of ec18152: autobuild-preview-pr-750-ec18152e

robobun added a commit to oven-sh/bun that referenced this pull request Oct 1, 2026
This is the preview build of oven-sh/WebKit#750: f20ce77445 plus the
matcher. It becomes the merged commit once that pull request lands.
@robobun
robobun force-pushed the robobun/96d7caac/yarr-linear-engine branch 3 times, most recently from 36f2026 to 6830e12 Compare October 2, 2026 06:35
robobun added a commit to oven-sh/bun that referenced this pull request Oct 2, 2026
--experimental-linear-regexp and BUN_FEATURE_FLAG_EXPERIMENTAL_LINEAR_REGEXP=1
set JavaScriptCore's useRegExpLinearEngine before it starts. A RegExp then
runs on JavaScriptCore's non-backtracking matcher when the matcher accepts its
pattern, and one match takes time linear in the length of its subject. A
pattern the matcher refuses is compiled and run as it is without the switch.

The switch is the process's. bun_jsc::initialize resolves it, bun test
--parallel forwards it to its workers, and a Worker whose execArgv has it
throws ERR_WORKER_INVALID_EXEC_ARGV in a process that does not have it.

WEBKIT_VERSION is the preview build of oven-sh/WebKit#750, which has the
matcher.
@robobun
robobun force-pushed the robobun/96d7caac/yarr-linear-engine branch 3 times, most recently from 33a20ad to ec05001 Compare October 7, 2026 20:17
robobun added a commit to oven-sh/bun that referenced this pull request Oct 8, 2026
--experimental-linear-regexp and BUN_FEATURE_FLAG_EXPERIMENTAL_LINEAR_REGEXP=1
set JavaScriptCore's useRegExpLinearEngine before it starts. A RegExp then
runs on JavaScriptCore's non-backtracking matcher when the matcher accepts its
pattern, and one match takes time linear in the length of its subject. A
pattern the matcher refuses is compiled and run as it is without the switch.

The switch is the process's. bun_jsc::initialize resolves it, bun test
--parallel forwards it to its workers, and a Worker whose execArgv has it
throws ERR_WORKER_INVALID_EXEC_ARGV in a process that does not have it.

WEBKIT_VERSION is the preview build of oven-sh/WebKit#750, which has the
matcher.
@robobun
robobun force-pushed the robobun/96d7caac/yarr-linear-engine branch 2 times, most recently from e896397 to 809b157 Compare October 8, 2026 15:41
The YARR JIT and the bytecode interpreter match by backtracking. A pattern
such as /(a*)*b/ costs them a number of steps that is exponential in the
length of the subject, and /a*a*a*a*a*a*a*a*b/ a polynomial one.

With --useRegExpLinearEngine=1 (default false), RegExp::compile() and
RegExp::compileMatchOnly() first ask Yarr::byteCompileLinear() for a program
for a nondeterministic automaton. When the matcher accepts the pattern, the
RegExp has bytecode that carries the program and no JIT code, and
Yarr::interpret() runs the program. The matcher advances every state of the
automaton over the subject together and enters no state twice at one
position, so the steps of a match grow with the length of the subject and
with nothing else. It keeps the states in the order backtracking tries them,
so the match and the captures are the ones the backtracking engines report.

The compiler takes two bounds from the program. The first is the most steps
a position of the subject can cost (LinearProgram::m_maximumStepsPerPosition).
Without a lookaround that is at most four steps per instruction. A lookaround
is run to its end at every position that asserts it, so lookarounds inside
one another multiply it, and the compiler refuses a program that can cost a
position more than four steps per instruction of the largest program. The
second is the most memory a match can hold (m_maximumScratchBytes). The
compiler counts the states and the frames of each code, and the matcher lets
none of its vectors grow past those counts.

The matcher refuses a backreference, a lookaround that can match a string of
any length, lookarounds that are too costly, groups more than 32 levels deep,
and a pattern whose program or working memory passes the limits
(maximumRegExpLinearProgramSize, maximumRegExpLinearWorkingMemory). A refused
pattern is compiled and run as it is without the option, by the JIT or by the
bytecode interpreter, and --reportRegExpLinearRefusals=1 prints a line for
each one. A refusal is about the pattern and about nothing else, and the
RegExp remembers it.

A RegExp asks the matcher once, before the JIT: Yarr::jitCompile() reorders
the terms of the pattern it is given. The compiler also refuses a pattern
whose terms are out of order, whoever asks with it. When the stack has too
little room left for the compiler, the compile fails with the error of the
other stages of a compile (TooManyDisjunctions): the match throws, nothing is
remembered, and the next match asks again. Yarr::RegularExpression has the
interpreter and no other engine, and asks in its own compile.
Yarr::byteCompile() does not ask.

With --verifyRegExpLinearEngine=1 (for tests), the bytecode interpreter
matches again from the same start after each match of the matcher, and the
process ends when the two do not agree on the match or on the groups.

$vm.regExpMatchStatistics(regExp, string, start) reports the engine a RegExp
is compiled for, how many times the RegExps of the VM asked the matcher, and
the bounds, the steps and the working memory of one match, for tests that
assert how the cost grows without a clock. Its mode "backtracking" matches
with the bytecode interpreter, and its mode "outOfStack" makes the compiler of
the matcher find no stack. $vm.regExpMatchOnBothEngines(regExp, string, start)
matches one RegExp with the engine it is compiled for and with the bytecode
interpreter, and compares the two output vectors. The interpreter has a low
match limit there and reports when it gives up, because its answer is then
"no match" whatever the subject has. $vm.regExpLinearRefusalAfterJITCompile()
asks the matcher with a pattern the JIT has compiled.

JSTests/stress/regexp-linear-engine-*.js are the tests of the matcher:
regexp-linear-engine-differential.js compares it with the interpreter on 1.4
million matches. JSTests/regexpLinearEngine.yaml runs the RegExp tests of
JSTests/stress once more with the option and the verification, so that a
change of YarrPattern is checked against the matcher. Tools/yarr-fuzz has the
configurations "linear", "linear-interp" and "linear-verify", and reuses group
names across alternatives.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants