Prefilter rune-mode input for non-ASCII patterns
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The scan only ran for ASCII patterns, so searching CJK text with a CJK query still built the full score matrix. Scan for one byte of the pattern rune and verify all four. Which byte matters. Every ASCII rune contributes three zero bytes, so U+AE00 scanned by its zero low byte hits on nearly every character of an ASCII-heavy line. Pick a byte that cannot occur in an ASCII rune, else any non-zero one. A non-ASCII pattern rune is safe only when no other rune lowercases onto it. Uncased is not sufficient: U+00DF has no simple uppercase, yet U+1E9E lowercases to it, so the foldable set is excluded too. Measured on 1.4M-line corpora, with a non-ASCII query: - Every line CJK: 5.1x to 10.2x - Mostly-ASCII paths behind a Hangul prefix: 5.6x to 6.0x, and 1.2x where every line matches so nothing can be rejected - ASCII queries unchanged, kept off the non-inlinable guard
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+274 added−18 removed
- other:+274 added−18 removed
Provenance
- Commit
9dfdba4- Tree
9f879c9- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
465837f
5 files changed+274 added−18 removed
modified:src/algo/algo.go+60 added-18 removed
345 unmodified lines346 }347 return true348 }349 350-// runeFuzzyIndex is asciiFuzzyIndex for rune-mode input. Only valid when the351-// input cannot fold to ASCII, see the caller.350+// runePrefilterable reports whether scanning the rune array can decide this351+// pattern against this item without missing a match. Phase 2 lowercases an352+// uppercase text rune and then normalizes it, and the scan sees neither353+// transform, so every pattern rune must be unreachable by them.354+func runePrefilterable(input *util.Chars, pattern []rune, caseSensitive bool) bool {355+ if input.MayFoldToAscii() {356+ // A non-ASCII rune of this item could fold onto an ASCII pattern char357+ for _, r := range pattern {358+ if r < utf8.RuneSelf {359+ return false360+ }361+ }362+ }363+ if caseSensitive {364+ // No case transform is applied, and normalization only ever produces365+ // ASCII, so nothing can reach a non-ASCII pattern rune366+ return true367+ }368+ for _, r := range pattern {369+ // Another rune must not lowercase onto this one. Being uncased is not370+ // enough by itself: U+00DF has no simple uppercase yet U+1E9E371+ // lowercases to it. Excluding the foldable set covers that.372+ if r >= utf8.RuneSelf &&373+ (unicode.ToUpper(r) != r || unicode.ToLower(r) != r || util.MayFoldToAscii(r)) {374+ return false375+ }376+ }377+ return true378+}379+380+// runeFuzzyIndex is asciiFuzzyIndex for rune-mode input. Only valid when381+// runePrefilterable says so.382 func runeFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) {383 runes := input.Runes()384 firstIdx, idx, lastIdx := 0, 0, 0355- var b byte385+ var last rune386 for pidx := range pattern {357- b = byte(pattern[pidx])358- idx = indexAsciiRune(runes, caseSensitive, b, idx)387+ last = pattern[pidx]388+ if last < utf8.RuneSelf {389+ idx = indexAsciiRune(runes, caseSensitive, byte(last), idx)390+ } else {391+ idx = indexRune(runes, last, idx)392+ }393 if idx < 0 {394 return -1, -1395 }396 if pidx == 0 && idx > 0 {6 unmodified lines403 404 // Find the last appearance of the last character of the pattern to limit405 // the search scope406 if lastIdx+1 < len(runes) {373- if end := lastIndexAsciiRune(runes, caseSensitive, b, lastIdx+1); end >= 0 {407+ var end int408+ if last < utf8.RuneSelf {409+ end = lastIndexAsciiRune(runes, caseSensitive, byte(last), lastIdx+1)410+ } else {411+ end = lastIndexRune(runes, last, lastIdx+1)412+ }413+ if end >= 0 {414 return firstIdx, end + 1415 }416 }417 return firstIdx, lastIdx + 1418 }419 420 func asciiFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) {381- if !isAscii(pattern) {382- // An ASCII string cannot contain a non-ASCII character383- if input.IsBytes() {384- return -1, -1385- }386- // Rune input with a non-ASCII pattern is not filtered yet387- return 0, input.Length()388- }389-421 if !input.IsBytes() {391- // Case folding or normalization can turn a non-ASCII rune into the392- // ASCII character we are looking for, which the scan cannot see393- if disableRunePrefilter || input.MayFoldToAscii() {422+ if disableRunePrefilter {423 return 0, input.Length()424 }425+ // runePrefilterable does not inline, so keep the common case out of426+ // it: an ASCII pattern against an item that cannot fold to ASCII is427+ // always scannable, and both of these checks do inline.428+ if input.MayFoldToAscii() || !isAscii(pattern) {429+ if !runePrefilterable(input, pattern, caseSensitive) {430+ return 0, input.Length()431+ }432+ }433 return runeFuzzyIndex(input, pattern, caseSensitive)434 }435 436+ // Not possible437+ if !isAscii(pattern) {438+ return -1, -1439+ }440+441 firstIdx, idx, lastIdx := 0, 0, 0442 var b byte443 for pidx := range pattern {444 b = byte(pattern[pidx])897 unmodified linesmodified:src/algo/runeindex_others.go+8 added
11 unmodified lines12 13 func lastIndexAsciiRune(runes []rune, caseSensitive bool, b byte, from int) int {14 return lastIndexAsciiRuneRef(runes, caseSensitive, b, from)15 }16+17+func indexRune(runes []rune, r rune, from int) int {18+ return indexRuneRef(runes, r, from)19+}20+21+func lastIndexRune(runes []rune, r rune, from int) int {22+ return lastIndexRuneRef(runes, r, from)23+}modified:src/algo/runeindex_ref.go+18 added
33 unmodified lines34 }35 }36 return -137 }38+39+func indexRuneRef(runes []rune, r rune, from int) int {40+ for i := from; i < len(runes); i++ {41+ if runes[i] == r {42+ return i43+ }44+ }45+ return -146+}47+48+func lastIndexRuneRef(runes []rune, r rune, from int) int {49+ for i := len(runes) - 1; i >= from; i-- {50+ if runes[i] == r {51+ return i52+ }53+ }54+ return -155+}modified:src/algo/runeindex_x86.go+63 added
40 unmodified lines41 }42 return -143 }44 45+// runeNeedle picks which of the rune's four bytes to scan for, and returns its46+// lane index and value. A zero byte is a useless needle because every ASCII47+// rune contributes three of them, so U+AE00 scanned by its low byte would hit48+// on almost every character of an ASCII-heavy line. Prefer a byte that cannot49+// occur in an ASCII rune at all, then any non-zero byte.50+func runeNeedle(r rune) (int, byte) {51+ var b [4]byte52+ b[0], b[1], b[2], b[3] = byte(r), byte(r>>8), byte(r>>16), byte(r>>24)53+ for i, v := range b {54+ if v >= 0x80 {55+ return i, v56+ }57+ }58+ for i, v := range b {59+ if v != 0 {60+ return i, v61+ }62+ }63+ return 0, 064+}65+66+func runeAt(view []byte, start int) rune {67+ return rune(view[start]) | rune(view[start+1])<<8 | rune(view[start+2])<<16 | rune(view[start+3])<<2468+}69+70+// indexRune returns the index of the first rune equal to r at or after rune71+// index from. Case is not folded, so the caller must have established that no72+// other rune can transform into r.73+func indexRune(runes []rune, r rune, from int) int {74+ view := runeBytes(runes)75+ lane, needle := runeNeedle(r)76+ for off := from*4 + lane; off < len(view); {77+ idx := bytes.IndexByte(view[off:], needle)78+ if idx < 0 {79+ return -180+ }81+ pos := off + idx82+ if start := pos - lane; start&3 == 0 && runeAt(view, start) == r {83+ return start >> 284+ }85+ off = pos + 186+ }87+ return -188+}89+90+// lastIndexRune is indexRune scanning backwards from the end.91+func lastIndexRune(runes []rune, r rune, from int) int {92+ view := runeBytes(runes)93+ lane, needle := runeNeedle(r)94+ for end := len(view); end > from*4+lane; {95+ idx := bytes.LastIndexByte(view[from*4+lane:end], needle)96+ if idx < 0 {97+ return -198+ }99+ pos := from*4 + lane + idx100+ if start := pos - lane; start&3 == 0 && runeAt(view, start) == r {101+ return start >> 2102+ }103+ end = pos104+ }105+ return -1106+}107+108 // lastIndexAsciiRune is indexAsciiRune scanning backwards from the end.109 func lastIndexAsciiRune(runes []rune, caseSensitive bool, b byte, from int) int {110 view := runeBytes(runes)[from*4:]111 both := !caseSensitive && b >= 'a' && b <= 'z'17 unmodified linesmodified:src/algo/runeprefilter_test.go+125 added
253 unmodified lines254 }255 }256 }257 258+// Step G lets non-ASCII pattern runes use the scan, but only when no other259+// rune can transform into them. Being uncased is not sufficient: U+00DF has no260+// simple uppercase yet U+1E9E lowercases onto it. This pins the guard against261+// the full preimage relation over all of Unicode.262+func TestRunePrefilterableGuardIsSound(t *testing.T) {263+ preimage := map[rune][]rune{}264+ for r := rune(0); r <= unicode.MaxRune; r++ {265+ if r >= 0xD800 && r <= 0xDFFF {266+ continue267+ }268+ if charClassOfNonAscii(r) == charUpper {269+ if l := unicode.To(unicode.LowerCase, r); l != r {270+ preimage[l] = append(preimage[l], r)271+ }272+ }273+ }274+275+ clean := util.ToChars([]byte("漢字")) // rune mode, fold bit clear276+ admitted, violations := 0, 0277+ for r := rune(utf8.RuneSelf); r <= unicode.MaxRune; r++ {278+ if r >= 0xD800 && r <= 0xDFFF {279+ continue280+ }281+ if !runePrefilterable(&clean, []rune{r}, false) {282+ continue283+ }284+ admitted++285+ if extra := preimage[r]; len(extra) > 0 {286+ violations++287+ if violations <= 5 {288+ t.Errorf("guard admits U+%04X but %U lowercases onto it", r, extra)289+ }290+ }291+ }292+ t.Logf("guard admits %d non-ASCII pattern runes, unsound for %d", admitted, violations)293+294+ // The scripts this step exists for must be fully admitted.295+ for _, s := range []struct {296+ name string297+ lo, hi rune298+ }{{"CJK", 0x4E00, 0x9FFF}, {"Hangul", 0xAC00, 0xD7A3}, {"kana", 0x3040, 0x30FF},299+ {"Thai", 0x0E00, 0x0E7F}, {"emoji", 0x1F300, 0x1FAFF}} {300+ for r := s.lo; r <= s.hi; r++ {301+ if !runePrefilterable(&clean, []rune{r}, false) {302+ t.Errorf("%s U+%04X should be admitted", s.name, r)303+ break304+ }305+ }306+ }307+}308+309+// The Step G path must actually engage and reject, otherwise the equivalence310+// test above proves nothing about non-ASCII patterns.311+func TestNonAsciiPatternPrefilterEngages(t *testing.T) {312+ rng := rand.New(rand.NewSource(6))313+ parts := []string{"漢字", "한글", "src", "conf", "/", "мир", "🎉"}314+ engaged, rejected, narrowed, bypassed := 0, 0, 0, 0315+ for range 5000 {316+ var sb strings.Builder317+ for range 1 + rng.Intn(6) {318+ sb.WriteString(parts[rng.Intn(len(parts))])319+ }320+ chars := util.ToChars([]byte(sb.String()))321+ if chars.IsBytes() {322+ continue323+ }324+ pattern := []rune([]string{"漢", "漢字", "한글", "мир", "🎉", "é", "ß"}[rng.Intn(7)])325+ if !runePrefilterable(&chars, pattern, false) {326+ bypassed++327+ continue328+ }329+ engaged++330+ lo, hi := asciiFuzzyIndex(&chars, pattern, false)331+ switch {332+ case lo < 0:333+ rejected++334+ case hi-lo < chars.Length():335+ narrowed++336+ }337+ }338+ t.Logf("non-ASCII patterns: engaged %d, bypassed %d, rejected %d, narrowed %d",339+ engaged, bypassed, rejected, narrowed)340+ if engaged == 0 || rejected == 0 {341+ t.Fatalf("non-ASCII pattern path not exercised (engaged=%d rejected=%d)", engaged, rejected)342+ }343+ if bypassed == 0 {344+ t.Fatal("cased and foldable patterns should still bypass")345+ }346+}347+348+// indexRune picks which byte lane to scan, and is checked against the shipped349+// reference scanners rather than a copy of them. Zero-low-byte runes (U+AE00) and350+// runes whose lanes collide with common ASCII bytes are the cases that break a351+// naive low-byte scan, so the alphabet includes both.352+func TestIndexRuneMatchesReference(t *testing.T) {353+354+ alphabet := []rune{355+ 'a', 'e', 'N', '/', 0x00,356+ 0xAE00, 0xAC00, 0xD55C, // Hangul, low byte zero for U+AE00357+ 0x4E00, 0x6587, 0x9FFF, // CJK, U+4E00 has zero low byte358+ 0x3040, 0x0E00, // kana, Thai with zero low byte359+ 0x1F389, 0x1F300, // emoji, 3 significant bytes360+ 0x0100, 0x0165, 0x00E9, // low byte zero / ASCII-colliding lanes361+ }362+ rng := rand.New(rand.NewSource(7))363+ for trial := range 30000 {364+ n := rng.Intn(20)365+ runes := make([]rune, n)366+ for i := range runes {367+ runes[i] = alphabet[rng.Intn(len(alphabet))]368+ }369+ r := alphabet[rng.Intn(len(alphabet))]370+ from := 0371+ if n > 0 {372+ from = rng.Intn(n)373+ }374+ if got, exp := indexRune(runes, r, from), indexRuneRef(runes, r, from); got != exp {375+ t.Fatalf("trial %d: indexRune(%U, U+%04X, %d) = %d, expected %d", trial, runes, r, from, got, exp)376+ }377+ if got, exp := lastIndexRune(runes, r, from), lastIndexRuneRef(runes, r, from); got != exp {378+ t.Fatalf("trial %d: lastIndexRune(%U, U+%04X, %d) = %d, expected %d", trial, runes, r, from, got, exp)379+ }380+ }381+}382+383 // preparePattern mirrors what pattern.go guarantees the algo functions:384 // lowercased when case-insensitive, normalized when normalize is on.385 func preparePattern(pat string, caseSensitive, normalize bool) []rune {386 if !caseSensitive {93 unmodified lines