Add fast path for two-character patterns in FuzzyMatchV2
Before adoption: this commit came in with the history the project adopted, so no landing records it.
For two ASCII characters, rows 0 and 1 of the score matrix collapse to scalar running state, so Phase 2 and Phase 3 fuse into one pass with no score arrays. withPos stores the two rows for the backtrace. Up to 1.4x on two-char queries, the most common multi-char length. Verify both fast paths against the general algorithm with exhaustive (every short string over a class-complete alphabet) and fuzz tests, runnable via the new make fuzz target.
authored by Junegunn Choi · committed by Junegunn Choi · parent 2327221 · Browse files · 5 files·+410 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+410 added−3 removed
- other:+410 added−3 removed
Provenance
- Commit
f779e6a- Tree
5a3ee5b- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
2327221
5 files changed+410 added−3 removed
modified:src/algo/algo_test.go+72 added
239 unmodified lines240 break241 }242 }243 }244+245+// TestFuzzyMatchV2TwoEquivalence verifies that the two-character fast path246+// produces the same Result and positions as the general algorithm across247+// case sensitivity, direction, and withPos, using a reused slab to surface248+// any stale-data reads in the backtrace.249+func TestFuzzyMatchV2TwoEquivalence(t *testing.T) {250+ words := []string{"src", "main", "core", "config", "parser", "render", "server",251+ "client", "index", "handler", "util", "list", "cache", "reader"}252+ exts := []string{".go", ".rb", ".py", ".md", ".c", ".txt"}253+ // Deterministic corpus (LCG), plus adversarial short/repeated items254+ corpus := []util.Chars{}255+ seed := uint32(12345)256+ next := func(n int) int { seed = seed*1664525 + 1013904223; return int(seed>>8) % n }257+ for i := 0; i < 4000; i++ {258+ depth := 2 + next(4)259+ s := ""260+ for d := 0; d < depth; d++ {261+ if d > 0 {262+ s += "/"263+ }264+ s += words[next(len(words))]265+ if next(5) == 0 {266+ s += "_" + words[next(len(words))]267+ }268+ }269+ s += exts[next(len(exts))]270+ corpus = append(corpus, util.ToChars([]byte(s)))271+ }272+ for _, s := range []string{"", "a", "ab", "aa", "aXb", "a/b", "//", "..", "abcabc",273+ "AaBb", "x.y.z", "a_b_c", "CoreCore", " co"} {274+ corpus = append(corpus, util.ToChars([]byte(s)))275+ }276+277+ pats := []string{"co", "ab", "aa", "//", "..", "sr", "a/", "_c", "oo", "Ab",278+ "z.", "b.", "1a", "ll", "re", "er", "Co"}279+ slab := util.MakeSlab(100*1024, 2048)280+ for _, cs := range []bool{false, true} {281+ for _, fwd := range []bool{true, false} {282+ for _, wp := range []bool{false, true} {283+ for _, p := range pats {284+ pattern := []rune(p)285+ for j := range corpus {286+ disableTwo = true287+ rg, pg := FuzzyMatchV2(cs, false, fwd, &corpus[j], pattern, wp, slab)288+ disableTwo = false289+ rt, pt := FuzzyMatchV2(cs, false, fwd, &corpus[j], pattern, wp, slab)290+ if rg != rt {291+ t.Fatalf("Result cs=%v fwd=%v wp=%v pat=%q item=%q: general %v vs two %v",292+ cs, fwd, wp, p, corpus[j].ToString(), rg, rt)293+ }294+ if (pg == nil) != (pt == nil) || (pg != nil && !equalInts(*pg, *pt)) {295+ t.Fatalf("Pos cs=%v fwd=%v wp=%v pat=%q item=%q: general %v vs two %v",296+ cs, fwd, wp, p, corpus[j].ToString(), pg, pt)297+ }298+ }299+ }300+ }301+ }302+ }303+}304+305+func equalInts(a, b []int) bool {306+ if len(a) != len(b) {307+ return false308+ }309+ for i := range a {310+ if a[i] != b[i] {311+ return false312+ }313+ }314+ return true315+}modified:src/algo/algo.go+181 added-1 removed
461 unmodified lines462 pos := []int{maxScorePos}463 return result, &pos464 }465 466+// Test hooks: force the general path instead of a fast path, so the two can467+// be compared for equivalence.468+var (469+ disableSingle bool470+ disableTwo bool471+)472+473+// fuzzyMatchV2Two is a fused fast path for a two-character ASCII pattern on474+// ASCII input. It replicates Phase 2 (row 0) and Phase 3 (row 1) of475+// FuzzyMatchV2 in a single pass, carrying the row-0 diagonal/left values and476+// the row-1 left value as scalars instead of materializing score arrays.477+// When withPos is set, the two DP rows are stored so the backtrace can478+// recover the matched character positions, exactly as the general Phase 4.479+func fuzzyMatchV2Two(caseSensitive bool, forward bool, input *util.Chars, pchar0 byte, pchar1 byte, minIdx int, maxIdx int, withPos bool, slab *util.Slab) (Result, *[]int) {480+ sl := input.Bytes()481+ N := maxIdx - minIdx482+483+ // Row storage, only needed for the backtrace484+ var H0, C0, H1, C1 []int16485+ if withPos {486+ o := 0487+ o, H0 = alloc16(o, slab, N)488+ o, C0 = alloc16(o, slab, N)489+ o, H1 = alloc16(o, slab, N)490+ _, C1 = alloc16(o, slab, N)491+ }492+493+ maxScore, maxScorePos := int16(0), 0494+ prevClass := initialCharClass495+496+ // Subsequence tracking (equivalent to F[0], F[1] in Phase 2). The scope497+ // from asciiFuzzyIndex ends exactly at the last pchar1, so row 1's upper498+ // bound (Phase 3 lastIdx) is the final loop position; no separate var.499+ f0, f1 := -1, -1500+501+ // Row 0 running state at the previous position502+ var h0Prev, c0Prev, bPrev int16503+ inGap0 := false504+505+ // Row 1 running state506+ var h1Prev int16507+ inGap1 := false508+509+ for off := range N {510+ pos := minIdx + off511+ b := sl[pos]512+ class := asciiCharClasses[b]513+ lb := b514+ if !caseSensitive && b >= 'A' && b <= 'Z' {515+ lb = b + 32516+ }517+ bonus := bonusMatrix[prevClass][class]518+ prevClass = class519+520+ // Subsequence advance: pchar0 then pchar1521+ if f0 < 0 {522+ if lb == pchar0 {523+ f0 = off524+ }525+ } else if lb == pchar1 && f1 < 0 {526+ f1 = off527+ }528+529+ // Row 0 (pchar0)530+ var h0Cur, c0Cur int16531+ if lb == pchar0 {532+ h0Cur = scoreMatch + bonus*bonusFirstCharMultiplier533+ c0Cur = 1534+ inGap0 = false535+ } else {536+ if inGap0 {537+ h0Cur = max(h0Prev+scoreGapExtension, 0)538+ } else {539+ h0Cur = max(h0Prev+scoreGapStart, 0)540+ }541+ c0Cur = 0542+ inGap0 = true543+ }544+ if withPos {545+ H0[off], C0[off] = h0Cur, c0Cur546+ }547+548+ // Row 1 (pchar1), only within [f1, lastIdx]549+ if f1 >= 0 && off >= f1 {550+ var s1, s2, consecutive int16551+ hleft := h1Prev552+ if off == f1 {553+ hleft = 0554+ }555+ if inGap1 {556+ s2 = hleft + scoreGapExtension557+ } else {558+ s2 = hleft + scoreGapStart559+ }560+ if lb == pchar1 {561+ s1 = h0Prev + scoreMatch562+ bb := bonus563+ consecutive = c0Prev + 1564+ if consecutive > 1 {565+ fb := bPrev566+ if bb >= bonusBoundary && bb > fb {567+ consecutive = 1568+ } else {569+ bb = max(bb, bonusConsecutive, fb)570+ }571+ }572+ if s1+bb < s2 {573+ s1 += bonus574+ consecutive = 0575+ } else {576+ s1 += bb577+ }578+ }579+ inGap1 = s1 < s2580+ score := max(s1, s2, 0)581+ if forward && score > maxScore || !forward && score >= maxScore {582+ maxScore, maxScorePos = score, off583+ }584+ h1Prev = score585+ if withPos {586+ H1[off], C1[off] = score, consecutive587+ }588+ }589+590+ h0Prev, c0Prev, bPrev = h0Cur, c0Cur, bonus591+ }592+593+ if f1 < 0 {594+ return Result{-1, -1, 0}, nil595+ }596+ if !withPos {597+ return Result{minIdx + f0, minIdx + maxScorePos + 1, int(maxScore)}, nil598+ }599+600+ // Phase 4 backtrace, specialized to two rows. Mirrors the general loop:601+ // record a cell when it dominates its diagonal and left neighbors, then602+ // step up a row; otherwise step left. preferMatch breaks score ties and603+ // must not read row 1 left of f1 (unwritten, possibly stale slab data).604+ pos := posArray(true, 2)605+ i := 1606+ j := maxScorePos607+ preferMatch := true608+ for {609+ var s, s1, s2, cCur int16610+ if i == 1 {611+ s, cCur = H1[j], C1[j]612+ if j >= f1 {613+ s1 = H0[j-1]614+ }615+ if j > f1 {616+ s2 = H1[j-1]617+ }618+ } else {619+ s, cCur = H0[j], C0[j]620+ if j > f0 {621+ s2 = H0[j-1]622+ }623+ }624+ row := i625+ if s > s1 && (s > s2 || s == s2 && preferMatch) {626+ *pos = append(*pos, j+minIdx)627+ if i == 0 {628+ break629+ }630+ i--631+ }632+ preferMatch = cCur > 1 ||633+ row == 0 && j < N-1 && j+1 >= f1 && C1[j+1] > 0634+ j--635+ }636+ return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos637+}638+639 func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {640 // Assume that pattern is given in lowercase if case-insensitive.641 // First check if there's a match and calculate bonus for each position.642 // If the input string is too long, consider finding the matching chars in16 unmodified lines659 }660 661 // Single-character ASCII pattern needs neither the prefilter nor the662 // score matrix490- if M == 1 && input.IsBytes() && pattern[0] < utf8.RuneSelf {663+ if !disableSingle && M == 1 && input.IsBytes() && pattern[0] < utf8.RuneSelf {664 return fuzzyMatchV2Single(caseSensitive, forward, input, byte(pattern[0]), withPos)665 }666 667 // Phase 1. Optimized search for ASCII string3 unmodified lines671 }672 // fmt.Println(N, maxIdx, idx, maxIdx-idx, input.ToString())673 N = maxIdx - minIdx674 675+ // Two-character ASCII pattern: rows 0 and 1 collapse to scalar running676+ // state, so the general score arrays are unnecessary677+ if !disableTwo && M == 2 && input.IsBytes() &&678+ pattern[0] < utf8.RuneSelf && pattern[1] < utf8.RuneSelf {679+ return fuzzyMatchV2Two(caseSensitive, forward, input, byte(pattern[0]), byte(pattern[1]), minIdx, maxIdx, withPos, slab)680+ }681+682 // Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages683 offset16 := 0684 offset32 := 0685 offset16, H0 := alloc16(offset16, slab, N)573 unmodified linesadded:src/algo/fastpath_equiv_test.go+143 added
1+package algo2+3+// Equivalence tests for the single- and two-character fast paths against the4+// general FuzzyMatchV2 algorithm, which serves as the oracle.5+//6+// Two complementary strategies:7+// - Exhaustive: every string up to a fixed length over an alphabet that8+// covers all ASCII character classes, so every local scoring branch is9+// exercised (not merely sampled).10+// - Fuzz: coverage-guided, arbitrary length, to reach cases the bounded11+// exhaustive sweep cannot (e.g. long gaps where a high score decays).12+13+import (14+ "testing"15+16+ "github.com/junegunn/fzf/src/util"17+)18+19+// One char of each ASCII class that affects scoring: lower, upper, delimiter,20+// number, non-word, whitespace.21+var equivAlphabet = []byte{'a', 'B', '/', '1', '_', ' '}22+23+func samePos(a, b *[]int) bool {24+ if (a == nil) != (b == nil) {25+ return false26+ }27+ if a == nil {28+ return true29+ }30+ return equalInts(*a, *b)31+}32+33+// compareFastPath runs a single input/pattern/params pair through both the34+// fast path and the general algorithm and fails on any difference.35+func compareFastPath(t *testing.T, chars *util.Chars, pattern []rune, cs, fwd, wp bool, disable *bool, slab *util.Slab) {36+ t.Helper()37+ *disable = true38+ rg, pg := FuzzyMatchV2(cs, false, fwd, chars, pattern, wp, slab)39+ *disable = false40+ rt, pt := FuzzyMatchV2(cs, false, fwd, chars, pattern, wp, slab)41+ if rg != rt || !samePos(pg, pt) {42+ t.Fatalf("mismatch item=%q pat=%q cs=%v fwd=%v wp=%v: general %v %v vs fast %v %v",43+ chars.ToString(), string(pattern), cs, fwd, wp, rg, pg, rt, pt)44+ }45+}46+47+// lowerPattern lowercases the pattern for case-insensitive search, matching48+// the Algo contract (the pattern is pre-lowercased by BuildPattern).49+func lowerPattern(p []rune, cs bool) []rune {50+ if cs {51+ return p52+ }53+ out := make([]rune, len(p))54+ for i, c := range p {55+ if c >= 'A' && c <= 'Z' {56+ c += 3257+ }58+ out[i] = c59+ }60+ return out61+}62+63+func runExhaustive(t *testing.T, patLen, maxLen int, disable *bool) {64+ // All patterns of length patLen over the alphabet65+ var pats [][]rune66+ var genPat func(cur []rune)67+ genPat = func(cur []rune) {68+ if len(cur) == patLen {69+ pats = append(pats, append([]rune(nil), cur...))70+ return71+ }72+ for _, c := range equivAlphabet {73+ genPat(append(cur, rune(c)))74+ }75+ }76+ genPat(nil)77+78+ slab := util.MakeSlab(100*1024, 2048)79+ buf := make([]byte, 0, maxLen)80+ var rec func(depth int)81+ rec = func(depth int) {82+ chars := util.ToChars(append([]byte(nil), buf...))83+ for _, cs := range []bool{false, true} {84+ for _, fwd := range []bool{true, false} {85+ for _, wp := range []bool{false, true} {86+ for _, p := range pats {87+ compareFastPath(t, &chars, lowerPattern(p, cs), cs, fwd, wp, disable, slab)88+ }89+ }90+ }91+ }92+ if depth == maxLen {93+ return94+ }95+ for _, c := range equivAlphabet {96+ buf = append(buf, c)97+ rec(depth + 1)98+ buf = buf[:len(buf)-1]99+ }100+ }101+ rec(0)102+}103+104+func TestFuzzyMatchV2SingleExhaustive(t *testing.T) {105+ runExhaustive(t, 1, 6, &disableSingle)106+}107+108+func TestFuzzyMatchV2TwoExhaustive(t *testing.T) {109+ runExhaustive(t, 2, 6, &disableTwo)110+}111+112+func fuzzFastPath(f *testing.F, patLen int, disable *bool) {113+ f.Add("core_color/view/server.txt", "co")114+ f.Add("a b", "ab")115+ f.Add("XyZ/123_abc.def", "z1")116+ f.Add("aaaaaaaaaaaaaaaaaaaaaaaa", "aa")117+ slab := util.MakeSlab(200*1024, 4096)118+ f.Fuzz(func(t *testing.T, input, pat string) {119+ r := []rune(pat)120+ if len(r) != patLen {121+ return122+ }123+ for _, c := range r {124+ if c >= 128 {125+ return126+ }127+ }128+ chars := util.ToChars([]byte(input))129+ if !chars.IsBytes() {130+ return131+ }132+ for _, cs := range []bool{false, true} {133+ for _, fwd := range []bool{true, false} {134+ for _, wp := range []bool{false, true} {135+ compareFastPath(t, &chars, lowerPattern(r, cs), cs, fwd, wp, disable, slab)136+ }137+ }138+ }139+ })140+}141+142+func FuzzFuzzyMatchV2Single(f *testing.F) { fuzzFastPath(f, 1, &disableSingle) }143+func FuzzFuzzyMatchV2Two(f *testing.F) { fuzzFastPath(f, 2, &disableTwo) }modified:CHANGELOG.md+4 added-2 removed
1 unmodified line2 =========3 4 0.74.25 ------6-- Single-character queries are up to 2.4x faster7- - This is the most latency-sensitive case; the first keystroke scans the entire list before the result cache can help6+- Performance optimizations for short queries7+ - The most critical case: fzf narrows results as you type, so short queries scan the largest candidate sets and the first keystroke scans the whole input.8+ - Single-character queries are up to 2.4x faster9+ - Two-character queries are up to 1.4x faster10 - Faster sorting of search results; the default two-criteria ranking skips redundant radix passes11 - Fixed nondeterministic match highlight positions12 - fzf now detects terminal resize on Windows in `--height` mode (#4790) (@Cyrus580529)13 - Fixed signal handler cleanup when fzf is used as a library; SIGINT/SIGTERM/SIGHUP and resize handlers no longer persist after `Run()` returns3396 unmodified linesmodified:Makefile+10 added
95 unmodified lines96 97 itest:98 ruby test/runner.rb99 100+# Actively fuzz the matcher fast paths against the general algorithm.101+# Go fuzzes one target at a time, so iterate. Override duration with102+# FUZZTIME (e.g. make fuzz FUZZTIME=5m).103+FUZZTIME ?= 30s104+fuzz:105+ @for t in FuzzFuzzyMatchV2Single FuzzFuzzyMatchV2Two; do \106+ echo "== $$t =="; \107+ $(GO) test -run '^$$' -fuzz "^$$t$$" -fuzztime $(FUZZTIME) ./src/algo || exit 1; \108+ done109+110 bench:111 cd src && SHELL=/bin/sh GOOS= $(GO) test -v -tags "$(TAGS)" -run=Bench -bench=. -benchmem112 113 lint: $(SOURCES) test/*.rb test/lib/*.rb ${BASH_SCRIPTS}119 unmodified lines