Repository navigation
Conversation
Some globs compile to a regex that backtracks without bound on an input that almost matches: +(*a), +(a|*a), *a*a*a*a*b and others take seconds on a few dozen characters. toRegex now classifies the backtracking of each regex it builds. A regex that cannot backtrack badly is returned as before, a plain RegExp. One that can keeps its source, flags and capture groups, and gets its own test() and exec(): the regex itself runs on inputs short enough to bound its work, and a DFA built from the same source decides longer ones. The parser and the regex source it emits are not changed, so no glob changes what it matches. The code is in lib/bounded and has no dependencies.
Classifying compares the loops of a regex in pairs, so makeRe on a glob of a hundred stars took over a second and one of three hundred over twenty. The classifier now counts its work and stops at 4,000 units; a regex over that is treated as one that can backtrack and is answered by the DFA. Ordinary globs use at most about 1,100 units. Adds a test that compiles and answers a glob of 300 stars in a child process with a deadline. It fails on the previous commit.
bardrop
left a comment
There was a problem hiding this comment.
I compared the DFA (dfa: 'always') with the plain regex on random globs (extglobs to depth 2, classes, braces, nocase, dot, contains, windows, ...) and short random names: 17 million comparisons with no difference. The globs that took seconds were all slow on master only. Three things came up around it, inline.
|
|
||
| class TooLarge extends Error {} | ||
|
|
||
| const table = new Map(); |
There was a problem hiding this comment.
This table is module level and nothing ever leaves it, so every term of every glob stays in memory for the life of the process. unguardMemo here and limits in backtracking.js grow the same way.
for (let i = 0; i <= 40000; i++) {
if (i % 10000 === 0) { global.gc(); console.log(i, Math.round(process.memoryUsage().heapUsed / 1e6) + ' MB'); }
picomatch.makeRe('+(*w' + i + ')').test('xxxxxx/');
}| distinct globs | master | this PR |
|---|---|---|
| 10,000 | 8 MB | 41 MB |
| 20,000 | 11 MB | 78 MB |
| 40,000 | 11 MB | 156 MB |
That matters for the case this PR is about, where the globs come from outside. The terms only have to be shared inside one DFA, so table and unguardMemo could be created in derivatives(tree) and go away with the regex; limits could have a size cap.
| return dfa.test(text); | ||
| } catch (err) { | ||
| if (!(err instanceof TooLarge)) throw err; | ||
| fallback = err.message; |
There was a problem hiding this comment.
The name alone can switch the protection off, with a short glob. +(*a)?????????????? (14 ?) has more than 4,000 reachable DFA states, so one long name that matches quickly is enough, and from then on that regex backtracks on every input:
const re = picomatch.makeRe('+(*a)??????????????');
let name = '', r = 1;
for (let i = 0; i < 9000; i++) { r = (Math.imul(r, 1664525) + 1013904223) >>> 0; name += (r >>> 30) & 1 ? 'a' : 'b'; }
re.test('a'.repeat(42) + '/'); // 1 ms
re.test(name + 'a'.repeat(15)); // true, 12 ms, fallback is now set
re.test('a'.repeat(42) + '/'); // 3,699 ms, about 2x for each extra 'a' (38: 243 ms, 40: 878 ms)The limit is listed in the PR text, but it reads as a limit on the glob, and here the glob is fixed and only the name is hostile.
When the limit is hit, the machine could drop terms, index and trans and go on from the current term as the only state (RE2 does this with its cache). That keeps memory bounded and the time linear, and the fallback is not needed.
| if (seen.has(t.id)) return; | ||
| seen.add(t.id); | ||
| if (t.k === 'chars') sets.push(t.set); | ||
| for (const c of [t.a, t.b, t.y, ...(t.items || [])]) if (c) collect(c); |
There was a problem hiding this comment.
collect recurses once per item of the sequence, so a long glob now throws from the matcher where master answers:
picomatch('a'.repeat(9000) + '*b*c*')('a'.repeat(9000) + 'bxx');
// master: false
// this PR: RangeError: Maximum call stack size exceeded7,000 characters is already enough here (Node 24, default stack), and the default maxLength is 65,536. unguard and seq recurse along the sequence too. Catching RangeError next to TooLarge would stop the throw, but a loop over an explicit stack in collect keeps these globs on the DFA.
- The term table was module level, so every term of every glob stayed for the life of the process. It now belongs to one DFA. Kept limits are capped at 1,000 sources of at most 2,000 characters. - A DFA past 4,000 states handed the regex back for every later input, and one long name was enough to get there. At the limit the table is now emptied and started again from the start state and the state reached. - The sequence builder, the guard remover and the set collector took a call per term and overflowed the stack on a glob of 9,000 characters. They walk in loops. A stack overflow that still happens, in the reader or in a derivative, leaves the answer to the plain regex.
A regex with no loop is linear, and its bound can still be out of reach: ?(a) repeated 55 times reads one prefix in about 2 to the 52nd ways. It came back as the plain RegExp and gave no answer in 2 s on 'a' x 144. The readings of a prefix are now counted for every such regex, and one with more than 16 gets the DFA for every input. Ordinary globs have at most 7.
|
Hi @bardrop, thanks for taking the time to take a look at the work, out of curiosity what was the part the intrigued you the most about this piece? I am always interested in hearing what other people look for when they go through a change like this. all three reproduce here as written and the branch now changes each one. numbers are from your snippets on Node 24.19.0. memory: the term table and the unguard memo are made per DFA now and go away with the regex. state limit: at 4,000 states the table is emptied and started again from the start state and the state just reached, with their terms made again in a fresh table. the fallback for that case is gone. In your snippet the long name takes 37 ms with one restart, and stack: after that I ran one glob shape at a time over a grid of glob sizes and name lengths, on master and on the branch, and it turned up more.
two things are not fixed and both are in the description's limits:
|
- The classifier did not look inside a lookahead, so !(+(*a)) was called linear and got the plain RegExp. Each body is now classified as a regex of its own and its work added. - When the DFA said yes, exec() ran the regex for its groups, and the regex can take exponential time before the match: @(+(*a)c|*b) on 'a' x 40 + 'b' gave no answer in 20 s through isMatch. The groups now come from a matcher that follows the engine's order and marks each place that failed, so no step is taken twice. A matching name on an exponential glob costs 0.7 to 4.4 us, where the regex takes under 0.1. The tests get one timeout of their own: one took up to 1.8 s of mocha's default 2 s.
The groups of a matching name came from a matcher that steps in JavaScript: 4.4 us for a test file on the Jest glob, where the regex takes 0.06. The ways the regex can read the name at hand are now counted along it, and the regex runs where the work they allow is small. The same name takes 0.16 us. A loop whose body can be empty, as in +(!(a)), is still left to the matcher.
With the contains option the regex has no ^ and is tried from every start. The classifier read it from one, so *a was called linear and got the plain RegExp, which takes 336 ms on a near miss of 40,000 letters and four times that for each doubling. A polynomial one got a limit one power too high.
The classifier chained two slow parts only where one ended in the loop
the next began with, so *a*a/*a*a/*a*a was called quadratic and got the
plain regex up to 1,000 characters. It is n^4: a 996 character name took
32 seconds, as it does without this branch.
A glob with a bracket that matches nothing, such as {[^\w\W]*a*a,lib},
made the classifier throw, and toRegex turned that into a regex that
matches nothing.
Some globs compile to a regex that takes exponential or polynomial time on an input that almost matches (CWE-1333). This gives those regexes a
test()andexec()that use a DFA, so the time grows with the length of the input, subject to the limits below. The parser and the regex source are unchanged, and the existing tests show no change in what a glob matches. It makes no security claim.It is a different approach from the open PRs that rewrite particular extglob shapes (#264 to #277), so it is offered as an alternative to weigh, not a replacement for any of them.
What it does
toRegexis the one place a source becomes aRegExp. It now classifies the backtracking of each regex it builds, once:*.js,**/*.js,src/**/*.{ts,tsx}): the plainRegExpis returned, exactly as before.*a*,**/node_modules/**): the regex gets its owntest()andexec(). The regex itself runs on inputs short enough to bound its work; longer ones go to a DFA built from the same source.+(*a),+(a|*a)): the same two methods. The DFA decides everytest(), and everyexec()except on a name the regex can read in few ways, which is described below.A regex with no loop of either kind can still read one prefix in very many ways when optional parts follow each other:
?(a)repeated 55 times has about 2 to the 52nd readings ofax 27. So the readings of a prefix are counted for the first class, and a regex with more than 16 is treated like the exponential ones. Ordinary globs have at most 7.The body of a lookahead is classified as a regex of its own and its work added, so
!(+(*a))is treated as exponential. Most negated globs stay linear:!(*.test).jsand**/!(a|b)/*.jsget the plainRegExp.With the
containsoption a regex has no^and is tried from every start, so it is classified as a search:*ais linear as a whole match and quadratic there. On a near miss of 40,000 letters*atakes 336 ms on master and 1.3 ms here, and a call on a short name costs 0.97 to 1.09 times master on Node 24 and 1.07 to 1.56 on Node 12. A glob with no loop to fail in, such asa/b, stays a plainRegExp.The DFA is built only as far as inputs take it, and cannot backtrack. When it says no, the regex never runs. When it says yes,
exec()needs the capture groups, and the regex can take exponential time to come to them: in@(+(*a)c|*b)the first branch fails in every way it can before the second is tried. So past the limit the groups come from a matcher that tries things in the order the engine does and marks each place that failed, so no step is taken twice.That matcher is slow on the short names most callers have, so
exec()first counts the ways the regex can read this very name, one table read per character once the table is warm, and lets the regex answer where the work they allow is under 16,000 steps. Of 645,120 pairs of a glob and a name made to backtrack, 429,991 were let through, and no call on one took more than 17 us.The returned object keeps the source, flags and prototype of
new RegExp(source, flags).Classifying is itself capped. A regex too large to classify within a fixed amount of work is treated as one that can backtrack, and the DFA decides every input.
Each DFA has a table of its own, which goes away with the regex, and the table holds at most 4,000 states. When an input reaches one more, the table is emptied and started again from the start state and the state just reached. So the memory of one regex is bounded whatever the names are, and reaching the limit costs time, not the bound.
The code is in
lib/bounded, about 2,100 lines, with no dependencies.lib/picomatch.jschanges by three lines.Measurements
Each glob's regex on
prefix + pump.repeat(k) + '/', in a child process with a 2 s deadline, on Node 24.19.0. The script is at the end.+(*a)aa+aax k*(*a)a+aax k+(*)a+ax k+(a*)aa+aax k+(@(*a))aa+aax k+(a|*a)aa+aaax k+(a*|b)aa+aax k+(*a|b)aa+aax k+(!(a))a+ax k*(!(f))a+ax k@(*a)+aa+aax k(*a)+aa+aax k{*a,b}+aa+aax k*a*a*a*a*ba+aaaaaaaax k**/+(*.)+(spec|test).+(ts|js)?(x).a+.ax ksrc/**/*(*.)@(spec|test).[jt]s?(x)src/+.ax kThe times in the last column are each a first call in a fresh process, with the DFA states built during the call. The last two globs are the Jest
testMatchin the nrwl/nx and microsoft/fluentui presets and the one Nx generates.Lookaheads, and names that match
The same machine and deadlines of 20 s. The slow part of the first two globs is in a lookahead; the third matches, after a branch that fails. These globs are made up.
!(+(*a))ax 20 +//test!(+(*a))ax 40 +//test!(+(*a))ax 16384 +bisMatch!(+(a|*a))ax 20 +bisMatch!(+(a|*a))ax 16384 +bisMatch@(+(*a)c|*b)ax 20 +bisMatch@(+(*a)c|*b)ax 30 +bisMatch@(+(*a)c|*b)ax 100000 +bexec@(+(*a)c|*b)ax 1000000 +bexecSlow parts that a separator keeps apart
Single calls of
test. Until this PR's last commit the first and third were called quadratic and took the regex as long here as on master.*a*a/*a*a/*a*aax 331 three times, joined by/, then!*a*a/*a*aax 498 twice, joined by/, then!*(a)*(a)c*(b)*(b)c*(a)*(a)a,bandax 331, joined byc, then!A long chain of stars
*arepeated 100 times, tested onarepeated n times followed by//, each in a child process with a 20 s deadline. This glob is made up to show the mechanism; it is not from a project.Cost
Measured against master, in one process with the two taken in turn:
*.js,**/*.js,src/**/*.{ts,tsx}**/!(*.test|*.spec).{js,ts}(polynomial)**/node_modules/**(polynomial)**/+(*.)+(spec|test).+(ts|js)?(x)(exponential), three short names+(*a)onaaa,@(+(*a)c|*b)onab,{*a,b}+onbanana(exponential)!(+(*a))and+(!(a))onsome-name.js(exponential, left to the matcher)makeRe, a glob not seen beforemakeRe, a glob seen beforemakeRe,*ax 100, fresh processmakeRe,*ax 3000, fresh processSo ordinary globs cost the same per call, and a glob's first compile costs about twenty times more (about 230 us, once for each different glob). The globs that could backtrack are slower per call in exchange for a bound: two to five times on most names, and about forty to sixty times where the name is left to the matcher. A very large glob costs a few milliseconds more to compile: its regex is read once, and about 4 ms goes to classifying before the cap stops it.
Memory
makeRe('+(*w' + i + ')').test('xxxxxx/')for i up to 40,000, each regex dropped after its call, heap after a collection. The loop is from the review below.A name that takes a DFA past its state limit
+(*a)??????????????has more than 4,000 reachable states. One call on a 9,015-character name ofaandbthat matches reaches them, in 37 ms with one restart of the table. The near missax 42 +/then takes 0.1 ms, as it did before that name, and so doesax 20000 +/.Limits
String.prototype.splitbuilds a newRegExpfrom the one it is given, by the spec, so it still backtracks.test,exec,match,replaceandsearchare covered.\b, flags other thani) gets the plainRegExp, as before.?(a)repeated 3,000 times, where 500 is fine) is caught, and that regex answers alone from then on, as it does on master. Groups nested thousands deep are not read at all and get the plainRegExp.*arepeated 3,000 times takes about 2 s for one near miss of 3,002 characters, where master does not finish.?(a)repeated 377 times takes about 300 ms on a name that matches, where master takes 8 ms, and repeated 987 times about 3 s on a matching name of 144 characters, where master takes 15 ms, and 7.5 s on one of 987. Globs of that size are made up; none was found in a project.exec()take memory in proportion to the regex and the name: about 180 bytes per character for@(+(*a)c|*b), 180 MB on a name of a million characters. They are dropped when the call returns. A regex with more than 50,000 steps written out, or with loops that can be empty nested more than eight deep, keeps its ownexec()on names that match.+(!(a)), and the bound is loose where a loop is inside a lookahead, as in!(+(*a)). Names that match such globs are left to the matcher, at 3 to 4 us for a short one.containsoption has its groups from the matcher, which takes 7.7 ms onbx 40000 +afor*a, where the regex takes under 0.1 ms.**/!(*.test|*.spec).{js,ts}is called polynomial and pays the cost above; none of the 7 kinds of near miss tried, up to 8,000 characters, took the regex more than 0.1 ms.Tests
test/bounded.jsadds 35 tests: plainRegExpfor globs that cannot backtrack badly; near misses that finish, in a child process with a deadline; a glob of 300 stars that compiles and answers; a chain of 55 optional groups; source, flags, prototype and capture groups kept; the same answers as the regex alone; a glob of 30,000 characters; a chain too deep for the stack; a near miss after a name has taken the DFA past its limit; the same answers with a table of 2, 3 and 7 states; the heap after 10,000 distinct globs; the class and the readings of lookahead bodies; matching names that finish intest,exec,match,search,replaceandisMatch; the match and groups of the regex alone on every name of up to five characters; the engine's order on regexes picked to be hard; steps in proportion to the name; the count that lets the regex run held to a backtracker that counts its steps, on 972 regexes; what that count keeps; thecontainsoption; slow parts that a separator keeps apart; a bracket that matches nothing. The existing 1,998 tests pass unchanged on Node 12 to 24 andnpm run lintpasses. Twenty-one of the new tests fail on master, nine of them because they load a module of this PR.The measurement script