Fixups to AHO-CORASICK matching. #24937
@khwilliamson can you check out the bitmap for folded data please. I am not sure i used the inverted fold data properly.
We don't need this kind of block in C99, and I think it's distracting. But I would understand if you have a plan to make the block conditionally executed, and want to pre-space it
At first glance, on my dev VM.
my $x = ("A"x200_000_000)."cat"; $x =~ /walrus|cat/;': has gone from 5-6 times slower than pre-24712 to 2-3 times faster.
my $x = ("cat"x20_000_000)."cat"; while ($x =~ /walrus|cat/g) {} seems about 10% slower than on 5.44.0 though.
I'll start going through the commits in a bit.
* my $x = ("cat"x20_000_000)."cat"; while ($x =~ /walrus|cat/g) {} seems about 10% slower than on 5.44.0 though.
Scrap that, I mustn't have had the latest updates from this branch.
Does this need to check s < strend? Does s <= e not cover it (or could it not be made to cover it)?
uh, good catch, fixed.
my $x = ("cat"x20_000_000)."cat"; while ($x =~ /walrus|cat/g) {}
FWIW, this is the kind of benchmark I personally try to avoid. It doesn't do any work, so the timing is very artificial. Often when you put some kind of sane workload in the loop all of a sudden the 10% increase is a negligible increase because the work in the body swamps everything else.
S_regmatch comments at https://github.com/Perl/perl5/blob/e910fa18bdd07a8b2d0fe9247c03938a3882b3c9/regexec.c#L7318
say that:
/* Start-class filtering is disabled while trie prefix
* extraction is being brought into alignment with the
* executable start state. */
Could some of the same mechanisms introduced in this PR apply there too?
1. Is this the optimum order of checks for the fastest fail?
2. Could some of this be hoisted out of _S_find_byclass_ if it's unchanging across runs?
Is this a per-character thing being tracked inside a per-octet loop? Does it need to be done per octet, or is there a way to amortize or otherwise keep track until the octet loop ends?
Not sure if I'm understanding the implementation correctly, but I've got two main concerns that I'm still feeling out:
1. If the space to search contains repetition with a periodicity that a word doesn't capture - such as "ABCABC..." or "ABCDEABCDE...", then it seems like the search will essentially fall back to octet-at-a-time. In particular, this seems like users operating in a three-octets-per-char alphabet get a raw deal.
2. For users operating in a multi-octet alphabet, the start-octet of the trie might well match the start of every single character in that alphabet. For UTF8 patterns, would it be better the "start"-search to look for either (i) what looks like the final octet of the start-character, or (ii) the final octet that currently the BMH check looks for. Especially for longer automatons, should the UTF-8 case perform 2-3 more BHM probes to be more confident that the first/last characters really are a match?
Oh, I see that the interplay between BMH and start-octet search isn't quite what I'd originally pictured for UTF-8, so it's not as bad as all that.
@richardleach, following up on your last comment.
So, a bit of context for those not familiar with it. Boyer–Moore–Horspool matching is a variant of Boyer–Moore matching. The usual description searches for one string. We use a version adapted to finding positions where one of a set of strings might match.
It is easiest to picture with words of the same length. Suppose we have a bunch of six-octet words. BMH looks at the octet where a word would end, and uses a table to decide how far to advance. An entry of zero says “a word might end here, check further”. An entry of one says “advance one octet and check again”. An octet which appears nowhere in our words can have an entry of six, allowing us to skip six octets.
With varying word lengths, we use a common prefix length determined by the shortest word, subject to the table’s size limit. So the anchor is not necessarily the last octet of a longer word. We build separate BMH tables for native and UTF-8 targets.
We combine this with a check of the possible first octet. If the end-position check looks promising but the first octet cannot start any word, we can reject that position without entering Aho–Corasick proper.
The repeat scanner handles another part of this process. After checking a machine-word-sized window and finding no possible starts, we know that identical following windows cannot contain a start either. We can then chew through repeated data a machine word at a time. This is useful for long runs of spaces, where repeatedly consulting the BMH table can cost more than comparing and skipping a whole word.
Your point about odd-sized repeats led to another improvement. The scanner now handles periods of 3, 5, 6 and 7 octets as well. The trick is to compare enough machine words that the repeating sequence returns to the same position at each block boundary. On a 64-bit build, a three-octet repeat lines up again after three machine words, or 24 octets. This is particularly useful for Unicode whitespace, since many Unicode spaces occupy three UTF-8 octets.
These shortcuts apply when AC is at its root, with no partial word in progress. Once matching has started, AC transitions and failure links keep track of the possible words. When it returns to the root, the scanning shortcuts become available again.
I also tested restricting repeat detection according to the BMH shift, and adding a cheap probe before doing more repeat checks. Both helped some inputs and hurt others, so neither was retained as a general rule. The right choice depends on both the search words and the input. I do not think we have a useful universal cutoff yet.
Anyway, here are some numbers from the latest version. Times are arithmetic means in microseconds per benchmark iteration, from twelve interleaved samples with matching compiler settings. Negative percentages mean less time. These compare the complete builds, rather than isolating any one optimisation.
| Workload | 5.44 µs | blead µs | Latest µs | Change vs 5.44 | Change vs blead |
|---|---:|---:|---:|---:|---:|
| Native ASCII, period 1 | 26.25 | 139.45 | 3.51 | −86.6% | −97.5% |
| Native ASCII, period 2 | 21.18 | 118.12 | 2.83 | −86.6% | −97.6% |
| Native ASCII, period 3 | 20.91 | 114.83 | 3.81 | −81.8% | −96.7% |
| Native ASCII, period 4 | 20.91 | 112.70 | 2.87 | −86.3% | −97.5% |
| Native ASCII, period 5 | 21.11 | 117.03 | 3.00 | −85.8% | −97.4% |
| Native ASCII, period 6 | 21.06 | 117.89 | 3.88 | −81.6% | −96.7% |
| Native ASCII, period 7 | 22.02 | 121.35 | 3.07 | −86.0% | −97.5% |
| Native ASCII, period 8 | 21.25 | 115.82 | 2.76 | −87.0% | −97.6% |
| UTF-8, different first octet | 53.75 | 198.01 | 24.27 | −54.8% | −87.7% |
| UTF-8, shared first octet | 154.39 | 150.13 | 32.47 | −79.0% | −78.4% |
| UTF-8, shared first and last octets | 160.67 | 150.36 | 130.13 | −19.0% | −13.5% |
| Unicode whitespace, period 3 | 27.19 | 98.47 | 2.61 | −90.4% | −97.3% |
| Unicode whitespace, period 5 | 32.10 | 100.84 | 2.16 | −93.3% | −97.9% |
| Unicode whitespace, period 6 | 26.52 | 101.99 | 2.59 | −90.2% | −97.5% |
| Unicode whitespace, period 7 | 34.12 | 99.78 | 1.95 | −94.3% | −98.0% |
| HTML, absent attribute names | 115.93 | 230.87 | 63.81 | −45.0% | −72.4% |
| Variable search in Perl source | 185.94 | 280.20 | 220.86 | +18.8% | −21.2% |
| Variable search in heavily indented Perl | 38.33 | 117.84 | 51.39 | +34.1% | −56.4% |
| Anchored native Latin-1, long words | 1.15 | 1.52 | 1.41 | +22.7% | −7.0% |
| Anchored UTF-8 Latin-1, long words | 1.32 | 1.69 | 1.55 | +17.2% | −8.5% |
| Dense matches: 4,096 copies of cat | 5,427.46 | 5,717.69 | 6,124.62 | +12.8% | +7.1% |
The repeated-input cases have about 32 KiB before a final match. The whitespace cases use actual Unicode spaces. The document cases scan 32,768 characters. Each anchored iteration tries three strings: two successful matches and one failure. The dense case returns 4,096 matches and includes counting them and accumulating their lengths. Input preparation and initial pattern construction are outside the timer.
So, for example, scanning three-octet Unicode whitespace fell from 98.47 µs on blead to 2.61 µs here.
There are also metrics which have degraded since 5.44. The source-search and anchored Latin-1 cases above all improve with this patch sequence relative to blead, although they have not recovered all the lost ground. I have plans to address the remaining representation costs in a follow-up. Dense matching is a separate remaining case where the new code is still slower.
I have worked through the implementation feedback too: removed redundant bounds checks, reduced position tracking, and avoided conversions where the input is already in the representation the trie needs. Some apparently obvious changes consistently lost in measurement, so I left them out. Code layout also proved sensitive: changing how the loop was expressed changed the generated branches enough to matter.
Construction costs are separate. Building the folded start maps adds a few microseconds to the small compilation cases we measured. That is paid when constructing the regex, while the scanning improvements apply each time it runs.
I think we are now in good territory. Next PR I want to try a hypothetical TRIE V2, with completely separate native and UTF-8 tables and structs, so that we can remove more of the representation-handling work from execution. Tries starting using codepoints, switched to utf8, and now I think they need to do latin-1 codepoints and utf8 octets. Sigh. Suggestions for further improvements are very welcome.
1. We now check NO_LATIN1_WORDS before the defensive trie-shape checks. We kept that change.
2. I also tried caching the invariant rejection condition and delaying the UTF-8 boundary calculation. Those versions helped some cases but slowed down Latin-1 and folded scans, so I dropped them.
Yes, good point. We removed the position ring entirely for case-sensitive matching, for both native and UTF-8 strings. We can subtract the matched word's input length instead. The UTF-8 case uses a byte length saved when we build the trie.
Folding still needs the ring because one input character can produce several folded characters. We now record character starts only, skip failed root transitions, and reset the cursor when a new candidate starts. The cursor also wraps with a comparison instead of modulo.
Never hardcode e9 or anything else below 0x100 unless you use one that is explicitly mentioned in perlhacktips.pod under "Assuming the character set is ASCIIish" which gives a pair usable in folding tests; or you can wrap strings in a sub from t/charset_tools.pl
You must have just revised this comment, as it makes more sense to me now. I've looked at it several times, and it didn't make sense.
I wonder, but do not claim to know, if it would make sense to exclude the /aa matches here, as it could be safely done here. I haven't looked at where the exclusion happens, though I've started to several times.
As explained in other comments. Don't use e9. This is 'Z' in EBCDIC, which I don't think is what you want.
No hard-coding constants < 0x100 in tests
Here, and elsewhere there may be macros that could avoid work for you that I just added documentation of to perlintern is_FOLDS_TO_MULTI_utf8 returns 0 if the UTF-8 input sequence does not fold to more than one character; otherwise it returns the number of bytes the foldable character occupies.
This is wrong. Like I said in an earlier review, you rarely have to worry about native vs Unicode in your code. Most operations are done in terms of native values. In this case, PL_HasMultiCharFold returns native values.
You're often doing the exact opposite of what is required. A bunch of tests use specific code points that are Unicode specific, ignoring that these have to be native values; whereas the code assumes you have to deal with native vs Unicode; and you don't. That may have been the original design, but it isn't any longer, so there's hardly any mention of EBCDIC in the current code base. But the test files still have to deal with it.
I think the rule to remember is that nearly everything is native. It's like Encode. It translates to/from the external character encoding. But the internal stuff is in the internal encoding, so you don't have to worry about it in your code. But you have to remember in tests to use that internal encoding
Otherwise, the algorithm looks right to me
Ok, sorry, yes i admit part of the lesson from before didnt sink in, but while I was following up on this I think I realized something that had been confusing me.
In the docs we say "Unicode" in places where as far as I now understand it we really accept a sort of hybrid "native-Unicode" where it is native codepoints for 0-255 and true Unicode for over 255. Is that correct? I mean, if i check the tests for toUPPER_uvchr that clearly show it accepts (and returns) the hybrid native-Unicode not true Unicode.
I wonder if the confusion related to this can be avoided by maybe using the term 'ncp' for 'native-(unicode)-codepoint' and use the term native-Unicode when we are talking about it in the docs. IMO this is one of the main reason I kept getting confused.
We have the functions NATIVE_TO_UNI() and UNI_TO_NATIVE() but it isnt really clear when they are needed. From what you say it seems like almost never in the internals?
I tried to rewrite some of the docs so others avoid my particular confusion. What do you think?
Yeah, sorry, that was left over from a refactor. Removed.
Right. Willdo in the future. Fixed.
>You must have just revised this comment,
Yes, and I just revised it again.
I wonder, but do not claim to know, if it would make sense to exclude the /aa matches here,
I am not sure I follow so I havent done anything with this yet.
Understood, fixed.
Thanks, I followed up on this. We are already iterating over PL_HasMultiCharFold, so we know each character folds to multiple characters. AFAICT we still need the folding call to find its first folded character, so the macro wouldn't save work in this loop. Am I missing something?
Hey @khwilliamson and @richardleach you have any objections on this? IMO it moves the needle in the right direction and I have further steps predicated on merging it.
A bunch of your commit messages begin with
fixup!
which makes no sense to me. I'm guessing these are notes to yourself; perhaps to squash.
Unicode guarantees that all folds contain 1, 2, or 3 characters. Hence at this point we know the answer is 2 or 3. There exists some macros that check the UTF-8 bytes to see if they are 3 character folds. That might be faster than calculating the length and the compiler might be able to optimize it better. Note that speed isn't particularly important during parsing. If you choose to go this route, the existing is_THREE_CHAR_FOLD_HEAD_utf8_safe would be best. It would be trivial for me or you to create a non-safe version with fewer checks by adding that to regen/regcharclass.pl. The is_MULTI_CHAR_FOLD_utf8_safe call has already ruled out non-safety.
I like the explanations about "'native-Unicode". There is text at the beginning of perlapi.pod that could stand to be updated with something like this. That might not need to go into this PR.
I'm not bothered by 'cp' vs 'ncp', but I'm more familiar with this stuff, so I would defer to you on this. But when I see 'ncp', I think of 'new' and not 'native'. Maybe there's a better term, such as 'vcp' or 'nvcp' or 'ntvcp'. In any case, it needs to be explained somewhere.
Many elements with 'uni' in their names DO refer to the Unicode values, not native. I'm trying to create and document 'uv' instead for people to use almost everywhere to mean the native-Unicode. Almost no one needs the straight Unicode
A bunch of your commit messages begin with
> > fixup!
> which makes no sense to me. I'm guessing these are notes to yourself; perhaps to squash.
They are specially formatted patches intended for autosquash.
git rebase -i --autosquash $branch
will automerge them into the relevant patch based on the subject line. Its so you can create a fixup patch and show it to someone without rebasing it together and obscuring the change. I did it to make my followups easier to review.
cheers,
Yves
I'm not bothered by 'cp' vs 'ncp', but I'm more familiar with this stuff, so I would defer to you on this. But when I see 'ncp', I think of 'new' and not 'native'. Maybe there's a better term, such as 'vcp' or 'nvcp' or 'ntvcp'. In any case, it needs to be explained somewhere.
I am not fussed on the names, but I think it would be nice to have a standard convention for stuff so arguments are self documenting to a certain extent.
So just in terms of getting this patch approved what do you want me to do? Undo the ncp change?
Several things that hardly are worth mentioning, except to educate readers of this not intimately familiar with these kinds of things. But this whole construct can be greatly simplified. See the comment below on the next source line.
uv_to_utf8. If it is broken, perl likely won't even compile. Maybe a non-reviewer would just skip over it. My guess is that you're checking that the new code's expectations are being met.uv_to_utf8 is probably better here. Seeing the current text makes me wonder why does the code need to use a 0 flag?assert(inRANGE(end - encoded, 1, 2)) could be used; it uses a single conditional. I've gotten in the habit of using it, so not using it stands out to me. Other readers might prefer the current text. Performance isn't an issue here; so it comes down to clarity for an average reader. I don't know the answer to that.assert(end - encoded == 1 || UTF8_IS_CONTINUATION(encoded[1]));There already exist some macros that make this loop simpler, and clearer.
for (i = 0; i < 256; i++) {
if (UVCHR_IS_INVARIANT(i)) {
PL_native_octet_utf8[i] = i;
}
else {
PL_native_octet_utf8[i] = (UTF8_EIGHT_BIT_HI(i) << 8)
| UTF8_EIGHT_BIT_LO(i);
}
}
I applied this macro-based approach with one order adjustment. The trie table stores the first encoded octet in the low byte of the U16 and the second in the high byte, as the executor reads the low byte first and then shifts by 8. So the packing is UTF8_EIGHT_BIT_HI(i) | ((U16)UTF8_EIGHT_BIT_LO(i) << 8). The expression in the example would reverse the order seen by the executor.
Agreed, thanks. The input is constrained to native values 0..255, so the length and validity assertions duplicate guarantees of the encoder. I replaced the encoder call, temporary buffer, and assertions with an invariant check and the existing UTF8_EIGHT_BIT_HI/LO macros.
The asserts were from when I was debugging during dev, and thought I had misunderstood how the function worked so added the asserts to be sure.
Thanks. I replaced utf8_length() with is_THREE_CHAR_FOLD_HEAD_utf8_safe() after the multi-character-fold check. That distinguishes the three-character folds from the two-character folds without counting UTF-8 characters during parsing.
Fixed: the test now converts U+00E9 with uni_to_native(), and the table-driven cases construct native characters with chr(). It no longer assumes that a value below 0x100 has the same character meaning on ASCII and EBCDIC.
Following up on your review: I renamed the to_uni_upper parameter from ncp to uv in the declaration and implementation, and added an explanation of native-Unicode numbering near the start of the generated perlapi documentation. The API introduction now explains the 0..255/native and above-255/Unicode split, when NATIVE_TO_UNI and UNI_TO_NATIVE are useful, and that older names containing uni may use native-Unicode values.
I left the start map as a conservative superset for /aa. The Unicode closure may admit extra candidates, but the executor applies the actual /aa folding rules, so those candidates cannot become false matches. A mode-specific restriction could reduce map hits, but it is a separate performance optimization; I did not add it without measuring a benefit.
Here and elsewhere. As I've mentioned elsewhere, I'm trying to standardize on a single style for naming functions and macros like this, so that you don't have to remember to use uvchr here and uni there, etc. And that new style is uv everywhere. As such, I'd prefer if you use uv_to_utf8 since it is new code. I need to mark in perlapi that the uvchr form is back-compat.
There's several places in this PR that a new uvchr is introduced
Hey @khwilliamson and @richardleach you have any objections on this? IMO it moves the needle in the right direction and I have further steps predicated on merging it.
I've not looked closely in more than a week. Will look this afternoon, but probably not going to be anything from me.
(In terms of juicing finding the start position: where 1-4 masks is enough to describe the possible start octet, a S_find_next_masked_n applying to 64 octets-at-a-time seems to have the potentially to be very fast, but I've not fully worked through it and wouldn't know how to wire it in / with what fallback. I can play with it some more / tidy ready to share if it sounds useful. Don't know what your follow-on plans are.)
I don't understand this. Isn't skiplen the same as UTF8SKIP(uc) (or SAFE_SKIP), and couldn't one just Copy uc to octet_buffer
Id like to get this applied, it has multiple good things in it, and I think does no new harm. Also I have a bunch of work predicated on it.
Id like to get this applied, it has multiple good things in it, and I think does no new harm. Also I have a bunch of work predicated on it.
I've got no new comments at present and don't want to hold you up at this stage in the dev cycle.
Only lingering concern is: how likely do you expect repeated UV blocks to feature in real-world workloads? Is it going to be enough for that part of the scanner to kick-in?
Only lingering concern is: how likely do you expect repeated UV blocks to feature in real-world workloads? Is it going to be enough for that part of the scanner to kick-in?
Anecdotally I think scanning documents with lots of whitespace is pretty common. But its a good question.
richardleach
demerphq
Resolve https://github.com/Perl/perl5/issues/24934 and
https://github.com/Perl/perl5/issues/24935.
Implements a grab bag of optimizations to the AHO-CORASICK start class optimization.
Uses Boyer-Moore-Horspool matching to construct a shift table which can allow scanning for the start of a match at very high speeds. (Think Boyer-Moore for a list of words.) However, BMH can slow things down in certain pathological cases, which is where we use a start class filter (similar to the old bitmap) to filter out bad starts, this combines with some logic to detect repeated short strings and consume them very quickly. The end result is that for the cases where the old bitmap was very fast we aren't quite as fast, but for the places where the bitmap was no help at all we can sometimes scream. Overall we seem to be very consistently fast, and sometimes very fast.
At the same time I added support for a start-octet map which uses the fold-inversion logic to build a bitmap we can use with utf8 folded data, which means case insensitive matches are now faster as well. Not as fast as case sensitive ones, alas.
There were also some other bookkeeping refinements which improved trie/ac matching, so even the base case got faster as well.
Lastly I found a bug that was introduced by the more aggressive prefix extraction that the octet patch included. An edge case that we hadnt encountered before, it is now fixed.
Median elapsed seconds; lower is faster. All builds use matching GCC 13.3
-O2settings, without debugging or threads.| Workload | Perl 5.44 | blead/ | Previous patch | Latest patch |
|---|---:|---:|---:|---:|
|
/walrus\|cat/, 200MAs +cat, Latin-1 | 0.3312 | 1.8074 | 0.4887 | 0.0478 || Same, UTF-8 flagged | 1.4617 | 1.8524 | 0.5023 | 0.0485 |
| 575 SV identifiers, source corpus, Latin-1 | 0.2730 | 0.4970 | 0.3206 | 0.2988 |
| Same source, UTF-8 flagged | 0.4455 | 0.5267 | 0.3097 | 0.3037 |
|
/walrus\|cat/, random ASCII, Latin-1 | 0.0176 | 0.1004 | 0.0266 | 0.0299 ||
/abcdefgh\|ijklmnop/, random ASCII, Latin-1 | 0.0178 | 0.1042 | 0.0101 | 0.0302 || Same, UTF-8 flagged | 0.0807 | 0.1028 | 0.0106 | 0.0327 |
|
/fooA\|barB/, repeatedAB, Latin-1 | 0.0683 | 0.4054 | 0.00572 | 0.00621 |Medians of three trials. The previous-patch column comes from the preceding benchmark run; the other three columns are fresh measurements.
Workload sizes:
Acase: three scans.AB: 1 MiB, scanned 128 times.