fork of https://github.com/sourcegraph/zoekt
0

Configure Feed

Select the types of activity you want to include in your feed.

1// Copyright 2016 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package search 16 17import ( 18 "bytes" 19 "context" 20 "flag" 21 "fmt" 22 "hash/fnv" 23 "io" 24 "log" 25 "math" 26 "os" 27 "reflect" 28 "runtime" 29 "sort" 30 "strconv" 31 "testing" 32 "testing/quick" 33 "time" 34 35 "github.com/RoaringBitmap/roaring" 36 "github.com/google/go-cmp/cmp" 37 "github.com/google/go-cmp/cmp/cmpopts" 38 "github.com/grafana/regexp" 39 40 "github.com/sourcegraph/zoekt/index" 41 42 "github.com/sourcegraph/zoekt" 43 "github.com/sourcegraph/zoekt/query" 44) 45 46func TestMain(m *testing.M) { 47 flag.Parse() 48 if !testing.Verbose() { 49 log.SetOutput(io.Discard) 50 } 51 os.Exit(m.Run()) 52} 53 54type crashSearcher struct{} 55 56func (s *crashSearcher) Search(ctx context.Context, q query.Q, opts *zoekt.SearchOptions) (*zoekt.SearchResult, error) { 57 panic("search") 58} 59 60func (s *crashSearcher) List(ctx context.Context, q query.Q, opts *zoekt.ListOptions) (*zoekt.RepoList, error) { 61 panic("list") 62} 63 64func (s *crashSearcher) Stats() (*zoekt.RepoStats, error) { 65 return &zoekt.RepoStats{}, nil 66} 67 68func (s *crashSearcher) Close() {} 69 70func (s *crashSearcher) String() string { return "crashSearcher" } 71 72func TestCrashResilience(t *testing.T) { 73 out := &bytes.Buffer{} 74 oldOut := log.Writer() 75 log.SetOutput(out) 76 defer log.SetOutput(oldOut) 77 78 ss := newShardedSearcher(2) 79 ss.ranked.Store([]*rankedShard{{Searcher: &crashSearcher{}}}) 80 81 var wantCrashes int 82 test := func(t *testing.T) { 83 q := &query.Substring{Pattern: "hoi"} 84 opts := &zoekt.SearchOptions{} 85 if res, err := ss.Search(context.Background(), q, opts); err != nil { 86 t.Fatalf("Search: %v", err) 87 } else if res.Stats.Crashes != wantCrashes { 88 t.Errorf("got stats %#v, want crashes = %d", res.Stats, wantCrashes) 89 } 90 91 if res, err := ss.List(context.Background(), q, nil); err != nil { 92 t.Fatalf("List: %v", err) 93 } else if res.Crashes != wantCrashes { 94 t.Errorf("got result %#v, want crashes = %d", res, wantCrashes) 95 } 96 } 97 98 // Before we are marked as ready we have one extra crash 99 wantCrashes = 2 100 t.Run("loading", test) 101 102 // After marking as ready we should only have the crashSearcher 103 // contributing. 104 ss.markReady() 105 wantCrashes = 1 106 t.Run("ready", test) 107} 108 109type rankSearcher struct { 110 rank uint16 111 repo *zoekt.Repository 112} 113 114func (s *rankSearcher) Close() { 115} 116 117func (s *rankSearcher) String() string { 118 return "" 119} 120 121func (s *rankSearcher) Search(ctx context.Context, q query.Q, opts *zoekt.SearchOptions) (*zoekt.SearchResult, error) { 122 select { 123 case <-ctx.Done(): 124 return &zoekt.SearchResult{}, nil 125 default: 126 } 127 128 // Ugly, but without sleep it's too fast, and we can't 129 // simulate the cutoff. 130 time.Sleep(time.Millisecond) 131 return &zoekt.SearchResult{ 132 Files: []zoekt.FileMatch{ 133 { 134 FileName: fmt.Sprintf("f%d", s.rank), 135 Score: float64(s.rank), 136 }, 137 }, 138 Stats: zoekt.Stats{ 139 MatchCount: 1, 140 }, 141 }, nil 142} 143 144func (s *rankSearcher) List(ctx context.Context, q query.Q, opts *zoekt.ListOptions) (*zoekt.RepoList, error) { 145 r := zoekt.Repository{} 146 if s.repo != nil { 147 r = *s.repo 148 } 149 r.Rank = s.rank 150 return &zoekt.RepoList{ 151 Repos: []*zoekt.RepoListEntry{ 152 {Repository: r}, 153 }, 154 }, nil 155} 156 157func (s *rankSearcher) Repository() *zoekt.Repository { return s.repo } 158 159func TestOrderByShard(t *testing.T) { 160 ss := newShardedSearcher(1) 161 162 n := 10 * runtime.GOMAXPROCS(0) 163 for i := range n { 164 ss.replace(map[string]zoekt.Searcher{ 165 fmt.Sprintf("shard%d", i): &rankSearcher{rank: uint16(i)}, 166 }) 167 } 168 169 if res, err := ss.Search(context.Background(), &query.Substring{Pattern: "bla"}, &zoekt.SearchOptions{}); err != nil { 170 t.Errorf("Search: %v", err) 171 } else if len(res.Files) != n { 172 t.Fatalf("empty options: got %d results, want %d", len(res.Files), n) 173 } 174 175 opts := zoekt.SearchOptions{ 176 TotalMaxMatchCount: 3, 177 } 178 res, err := ss.Search(context.Background(), &query.Substring{Pattern: "bla"}, &opts) 179 if err != nil { 180 t.Errorf("Search: %v", err) 181 } 182 183 if len(res.Files) < opts.TotalMaxMatchCount { 184 t.Errorf("got %d results, want %d", len(res.Files), opts.TotalMaxMatchCount) 185 } 186 if len(res.Files) == n { 187 t.Errorf("got %d results, want < %d", len(res.Files), n) 188 } 189 for i, f := range res.Files { 190 rev := n - 1 - i 191 want := fmt.Sprintf("f%d", rev) 192 got := f.FileName 193 194 if got != want { 195 t.Logf("%d: got %q, want %q", i, got, want) 196 } 197 } 198} 199 200func TestShardedSearcher_Ranking(t *testing.T) { 201 ss := newShardedSearcher(1) 202 203 var nextShardNum int 204 addShard := func(repo string, priority float64, docs ...index.Document) { 205 r := &zoekt.Repository{ID: hash(repo), Name: repo} 206 r.RawConfig = map[string]string{ 207 "public": "1", 208 "priority": strconv.FormatFloat(priority, 'f', 2, 64), 209 } 210 b := testShardBuilder(t, r, docs...) 211 shard := searcherForTest(t, b) 212 ss.replace(map[string]zoekt.Searcher{ 213 fmt.Sprintf("key-%d", nextShardNum): shard, 214 }) 215 nextShardNum++ 216 } 217 218 addShard("weekend-project", 20, index.Document{Name: "f2", Content: []byte("foo bas")}) 219 addShard("moderately-popular", 500, index.Document{Name: "f3", Content: []byte("foo bar")}) 220 addShard("weekend-project-2", 20, index.Document{Name: "f2", Content: []byte("foo bas")}) 221 addShard("super-star", 5000, index.Document{Name: "f1", Content: []byte("foo bar bas")}) 222 223 want := []string{ 224 "super-star", 225 "moderately-popular", 226 "weekend-project", 227 "weekend-project-2", 228 } 229 230 var have []string 231 for _, s := range ss.getLoaded().shards { 232 for _, r := range s.repos { 233 have = append(have, r.Name) 234 } 235 } 236 237 if !reflect.DeepEqual(want, have) { 238 t.Fatalf("\nwant: %s\nhave: %s", want, have) 239 } 240} 241 242func TestShardedSearcher_DocumentRanking(t *testing.T) { 243 ss := newShardedSearcher(1) 244 245 var nextShardNum int 246 addShard := func(repo string, rank uint16, docs ...index.Document) { 247 r := &zoekt.Repository{ID: hash(repo), Name: repo} 248 r.RawConfig = map[string]string{ 249 "public": "1", 250 } 251 r.Rank = rank 252 b := testShardBuilder(t, r, docs...) 253 shard := searcherForTest(t, b) 254 ss.replace(map[string]zoekt.Searcher{ 255 fmt.Sprintf("key-%d", nextShardNum): shard, 256 }) 257 nextShardNum++ 258 } 259 260 addShard("old-project", 1, index.Document{Name: "f1", Content: []byte("foobar")}) 261 addShard("recent", 2, index.Document{Name: "f2", Content: []byte("foobaz")}) 262 addShard("old-project-2", 1, index.Document{Name: "f3", Content: []byte("foo bar")}) 263 addShard("new", 3, index.Document{Name: "f4", Content: []byte("foo baz")}, 264 index.Document{Name: "f5", Content: []byte("fooooo")}) 265 266 // Run a stream search and gather the results 267 var results []*zoekt.SearchResult 268 opts := &zoekt.SearchOptions{ 269 FlushWallTime: 100 * time.Millisecond, 270 } 271 272 err := ss.StreamSearch(context.Background(), &query.Substring{Pattern: "foo"}, opts, 273 zoekt.SenderFunc(func(event *zoekt.SearchResult) { 274 results = append(results, event) 275 })) 276 if err != nil { 277 t.Fatal(err) 278 } 279 280 // There should always be two stream results, first progress-only, then the file results 281 if len(results) != 2 { 282 t.Fatalf("expected 2 streamed results, but got %d", len(results)) 283 } 284 285 // The ranking should be determined by whether it's an exact word match, 286 // followed by repository priority 287 want := []string{"f4", "f3", "f5", "f2", "f1"} 288 289 files := results[1].Files 290 got := make([]string, len(files)) 291 for i := range files { 292 got[i] = files[i].FileName 293 } 294 295 if !reflect.DeepEqual(got, want) { 296 t.Errorf("got %v, want %v", got, want) 297 } 298} 299 300func TestFilteringShardsByRepoSetOrBranchesReposOrRepoIDs(t *testing.T) { 301 ss := newShardedSearcher(1) 302 303 // namePrefix is so we can create a repo:foo filter and match the same set 304 // of repos. 305 namePrefix := [3]string{"foo", "bar", "baz"} 306 307 repoSetNames := []string{} 308 repoIDs := []uint32{} 309 n := 10 * runtime.GOMAXPROCS(0) 310 for i := range n { 311 shardName := fmt.Sprintf("shard%d", i) 312 repoName := fmt.Sprintf("%s-repository%.3d", namePrefix[i%3], i) 313 repoID := hash(repoName) 314 315 if i%3 == 0 { 316 repoSetNames = append(repoSetNames, repoName) 317 repoIDs = append(repoIDs, repoID) 318 } 319 320 ss.replace(map[string]zoekt.Searcher{ 321 shardName: &rankSearcher{ 322 repo: &zoekt.Repository{ID: repoID, Name: repoName}, 323 rank: uint16(n - i), 324 }, 325 }) 326 } 327 328 res, err := ss.Search(context.Background(), &query.Substring{Pattern: "bla"}, &zoekt.SearchOptions{}) 329 if err != nil { 330 t.Errorf("Search: %v", err) 331 } 332 if len(res.Files) != n { 333 t.Fatalf("no reposet: got %d results, want %d", len(res.Files), n) 334 } 335 336 branchesRepos := &query.BranchesRepos{List: []query.BranchRepos{ 337 {Branch: "HEAD", Repos: roaring.New()}, 338 }} 339 340 for _, name := range repoSetNames { 341 branchesRepos.List[0].Repos.Add(hash(name)) 342 } 343 344 set := query.NewRepoSet(repoSetNames...) 345 sub := &query.Substring{Pattern: "bla"} 346 347 repoIDsQuery := query.NewRepoIDs(repoIDs...) 348 repoQuery := &query.Repo{Regexp: regexp.MustCompile("^foo-.*")} 349 350 queries := []query.Q{ 351 query.NewAnd(set, sub), 352 // Test with the same reposet again 353 query.NewAnd(set, sub), 354 355 query.NewAnd(branchesRepos, sub), 356 // Test with the same repoBranches with IDs again 357 query.NewAnd(branchesRepos, sub), 358 359 query.NewAnd(repoIDsQuery, sub), 360 // Test with the same repoIDs again 361 query.NewAnd(repoIDsQuery, sub), 362 363 query.NewAnd(repoQuery, sub), 364 query.NewAnd(repoQuery, sub), 365 366 // List has queries which are just the reposet atoms. We also test twice. 367 set, 368 set, 369 branchesRepos, 370 branchesRepos, 371 repoIDsQuery, 372 repoIDsQuery, 373 repoQuery, 374 repoQuery, 375 } 376 377 for _, q := range queries { 378 res, err = ss.Search(context.Background(), q, &zoekt.SearchOptions{}) 379 if err != nil { 380 t.Errorf("Search(%s): %v", q, err) 381 } 382 // Note: Assertion is based on fact that `rankSearcher` always returns a 383 // result and using repoSet will half the number of results 384 if len(res.Files) != len(repoSetNames) { 385 t.Fatalf("%s: got %d results, want %d", q, len(res.Files), len(repoSetNames)) 386 } 387 } 388} 389 390func hash(name string) uint32 { 391 h := fnv.New32() 392 h.Write([]byte(name)) 393 return h.Sum32() 394} 395 396type memSeeker struct { 397 data []byte 398} 399 400func (s *memSeeker) Name() string { 401 return "memseeker" 402} 403 404func (s *memSeeker) Close() {} 405func (s *memSeeker) Read(off, sz uint32) ([]byte, error) { 406 return s.data[off : off+sz], nil 407} 408 409func (s *memSeeker) Size() (uint32, error) { 410 return uint32(len(s.data)), nil 411} 412 413func TestUnloadIndex(t *testing.T) { 414 b := testShardBuilder(t, nil, index.Document{ 415 Name: "filename", 416 Content: []byte("needle needle needle"), 417 }) 418 419 var buf bytes.Buffer 420 if err := b.Write(&buf); err != nil { 421 t.Fatal(err) 422 } 423 indexBytes := buf.Bytes() 424 indexFile := &memSeeker{indexBytes} 425 searcher, err := index.NewSearcher(indexFile) 426 if err != nil { 427 t.Fatalf("NewSearcher: %v", err) 428 } 429 430 ss := newShardedSearcher(2) 431 ss.replace(map[string]zoekt.Searcher{"key": searcher}) 432 433 var opts zoekt.SearchOptions 434 q := &query.Substring{Pattern: "needle"} 435 res, err := ss.Search(context.Background(), q, &opts) 436 if err != nil { 437 t.Fatalf("Search(%s): %v", q, err) 438 } 439 440 forbidden := byte(29) 441 for i := range indexBytes { 442 // non-ASCII 443 indexBytes[i] = forbidden 444 } 445 446 for _, f := range res.Files { 447 if bytes.Contains(f.Content, []byte{forbidden}) { 448 t.Errorf("found %d in content %q", forbidden, f.Content) 449 } 450 if bytes.Contains(f.Checksum, []byte{forbidden}) { 451 t.Errorf("found %d in checksum %q", forbidden, f.Checksum) 452 } 453 454 for _, l := range f.LineMatches { 455 if bytes.Contains(l.Line, []byte{forbidden}) { 456 t.Errorf("found %d in line %q", forbidden, l.Line) 457 } 458 } 459 } 460} 461 462func TestShardedSearcher_List(t *testing.T) { 463 repos := []*zoekt.Repository{ 464 { 465 ID: 1234, 466 Name: "repo-a", 467 Branches: []zoekt.RepositoryBranch{{Name: "main"}, {Name: "dev"}}, 468 RawConfig: map[string]string{"repoid": "1234"}, 469 }, 470 { 471 Name: "repo-b", 472 Branches: []zoekt.RepositoryBranch{{Name: "main"}, {Name: "dev"}}, 473 }, 474 } 475 476 doc := index.Document{ 477 Name: "foo.go", 478 Content: []byte("bar\nbaz"), 479 Branches: []string{"main", "dev"}, 480 } 481 482 // Test duplicate removal when ListOptions.Minimal is true and false 483 ss := newShardedSearcher(4) 484 ss.replace(map[string]zoekt.Searcher{ 485 "1": searcherForTest(t, testShardBuilder(t, repos[0], doc)), 486 "2": searcherForTest(t, testShardBuilder(t, repos[0])), 487 "3": searcherForTest(t, testShardBuilder(t, repos[1], doc)), 488 "4": searcherForTest(t, testShardBuilder(t, repos[1])), 489 }) 490 ss.markReady() 491 492 stats := zoekt.RepoStats{ 493 Shards: 2, 494 Documents: 1, 495 IndexBytes: 196, 496 ContentBytes: 13, 497 NewLinesCount: 1, 498 DefaultBranchNewLinesCount: 1, 499 OtherBranchesNewLinesCount: 1, 500 } 501 502 aggStats := stats 503 aggStats.Add(&aggStats) // since both repos have the exact same stats, this works 504 aggStats.Repos = 2 // Add doesn't populate Repos, this is done in Shards based on the response sizes. 505 506 for _, tc := range []struct { 507 name string 508 opts *zoekt.ListOptions 509 want *zoekt.RepoList 510 }{ 511 { 512 name: "nil opts", 513 opts: nil, 514 want: &zoekt.RepoList{ 515 Repos: []*zoekt.RepoListEntry{ 516 { 517 Repository: *repos[0], 518 Stats: stats, 519 }, 520 { 521 Repository: *repos[1], 522 Stats: stats, 523 }, 524 }, 525 Stats: aggStats, 526 }, 527 }, 528 { 529 name: "default", 530 opts: &zoekt.ListOptions{}, 531 want: &zoekt.RepoList{ 532 Repos: []*zoekt.RepoListEntry{ 533 { 534 Repository: *repos[0], 535 Stats: stats, 536 }, 537 { 538 Repository: *repos[1], 539 Stats: stats, 540 }, 541 }, 542 Stats: aggStats, 543 }, 544 }, 545 { 546 name: "field=repos", 547 opts: &zoekt.ListOptions{Field: zoekt.RepoListFieldRepos}, 548 want: &zoekt.RepoList{ 549 Repos: []*zoekt.RepoListEntry{ 550 { 551 Repository: *repos[0], 552 Stats: stats, 553 }, 554 { 555 Repository: *repos[1], 556 Stats: stats, 557 }, 558 }, 559 Stats: aggStats, 560 }, 561 }, 562 { 563 name: "field=reposmap", 564 opts: &zoekt.ListOptions{Field: zoekt.RepoListFieldReposMap}, 565 want: &zoekt.RepoList{ 566 Repos: []*zoekt.RepoListEntry{ 567 { 568 Repository: *repos[1], 569 Stats: stats, 570 }, 571 }, 572 ReposMap: zoekt.ReposMap{ 573 repos[0].ID: { 574 HasSymbols: repos[0].HasSymbols, 575 Branches: repos[0].Branches, 576 }, 577 }, 578 Stats: aggStats, 579 }, 580 }, 581 } { 582 tc := tc 583 t.Run(tc.name, func(t *testing.T) { 584 t.Parallel() 585 586 q := &query.Repo{Regexp: regexp.MustCompile("repo")} 587 588 res, err := ss.List(context.Background(), q, tc.opts) 589 if err != nil { 590 t.Fatalf("List(%v, %s): %v", q, tc.opts, err) 591 } 592 593 sort.Slice(res.Repos, func(i, j int) bool { 594 return res.Repos[i].Repository.Name < res.Repos[j].Repository.Name 595 }) 596 597 ignored := []cmp.Option{ 598 cmpopts.EquateEmpty(), 599 cmpopts.IgnoreFields(zoekt.MinimalRepoListEntry{}, "IndexTimeUnix"), 600 cmpopts.IgnoreFields(zoekt.RepoListEntry{}, "IndexMetadata"), 601 cmpopts.IgnoreFields(zoekt.RepoStats{}, "IndexBytes"), 602 cmpopts.IgnoreFields(zoekt.Repository{}, "SubRepoMap"), 603 cmpopts.IgnoreFields(zoekt.Repository{}, "priority"), 604 } 605 606 if diff := cmp.Diff(tc.want, res, ignored...); diff != "" { 607 t.Fatalf("mismatch (-want +got):\n%s", diff) 608 } 609 }) 610 } 611} 612 613func testShardBuilder(t testing.TB, repo *zoekt.Repository, docs ...index.Document) *index.ShardBuilder { 614 b, err := index.NewShardBuilder(repo) 615 if err != nil { 616 t.Fatalf("NewShardBuilder: %v", err) 617 } 618 619 for i, d := range docs { 620 if err := b.Add(d); err != nil { 621 t.Fatalf("Add %d: %v", i, err) 622 } 623 } 624 return b 625} 626 627func searcherForTest(t testing.TB, b *index.ShardBuilder) zoekt.Searcher { 628 var buf bytes.Buffer 629 if err := b.Write(&buf); err != nil { 630 t.Fatal(err) 631 } 632 f := &memSeeker{buf.Bytes()} 633 634 searcher, err := index.NewSearcher(f) 635 if err != nil { 636 t.Fatalf("NewSearcher: %v", err) 637 } 638 639 return searcher 640} 641 642func reposForTest(n int) (result []*zoekt.Repository) { 643 for i := range n { 644 result = append(result, &zoekt.Repository{ 645 ID: uint32(i + 1), 646 Name: fmt.Sprintf("test-repository-%d", i), 647 }) 648 } 649 return result 650} 651 652func testSearcherForRepo(b testing.TB, r *zoekt.Repository, numFiles int) zoekt.Searcher { 653 builder := testShardBuilder(b, r) 654 655 if err := builder.Add(index.Document{ 656 Name: fmt.Sprintf("%s/filename-%d.go", r.Name, 0), 657 Content: []byte("needle needle needle haystack"), 658 }); err != nil { 659 b.Fatal(err) 660 } 661 662 for i := 1; i < numFiles; i++ { 663 if err := builder.Add(index.Document{ 664 Name: fmt.Sprintf("%s/filename-%d.go", r.Name, i), 665 Content: []byte("haystack haystack haystack"), 666 }); err != nil { 667 b.Fatal(err) 668 } 669 } 670 671 return searcherForTest(b, builder) 672} 673 674func BenchmarkShardedSearch(b *testing.B) { 675 ss := newShardedSearcher(int64(runtime.GOMAXPROCS(0))) 676 677 filesPerRepo := 300 678 repos := reposForTest(3000) 679 var repoSetIDs []uint32 680 681 shards := make(map[string]zoekt.Searcher, len(repos)) 682 for i, r := range repos { 683 shards[r.Name] = testSearcherForRepo(b, r, filesPerRepo) 684 if i%2 == 0 { 685 repoSetIDs = append(repoSetIDs, r.ID) 686 } 687 } 688 689 ss.replace(shards) 690 691 ctx := context.Background() 692 opts := &zoekt.SearchOptions{} 693 694 needleSub := &query.Substring{Pattern: "needle"} 695 haystackSub := &query.Substring{Pattern: "haystack"} 696 helloworldSub := &query.Substring{Pattern: "helloworld"} 697 haystackCap, err := query.Parse("hay(s(t))(a)ck") 698 if err != nil { 699 b.Fatal(err) 700 } 701 702 haystackNonCap, err := query.Parse("hay(?:s(?:t))(?:a)ck") 703 if err != nil { 704 b.Fatal(err) 705 } 706 707 setAnd := func(q query.Q) func() query.Q { 708 return func() query.Q { 709 return query.NewAnd(query.NewSingleBranchesRepos("head", repoSetIDs...), q) 710 } 711 } 712 713 search := func(b *testing.B, q query.Q, wantFiles int) { 714 b.Helper() 715 716 res, err := ss.Search(ctx, q, opts) 717 if err != nil { 718 b.Fatalf("Search(%s): %v", q, err) 719 } 720 if have := len(res.Files); have != wantFiles { 721 b.Fatalf("wrong number of file results. have=%d, want=%d", have, wantFiles) 722 } 723 } 724 725 benchmarks := []struct { 726 name string 727 q func() query.Q 728 wantFiles int 729 }{ 730 {"substring all results", func() query.Q { return haystackSub }, len(repos) * filesPerRepo}, 731 {"substring no results", func() query.Q { return helloworldSub }, 0}, 732 {"substring some results", func() query.Q { return needleSub }, len(repos)}, 733 734 {"regexp all results capture", func() query.Q { return haystackCap }, len(repos) * filesPerRepo}, 735 {"regexp all results non-capture", func() query.Q { return haystackNonCap }, len(repos) * filesPerRepo}, 736 737 {"substring all results and repo set", setAnd(haystackSub), len(repoSetIDs) * filesPerRepo}, 738 {"substring some results and repo set", setAnd(needleSub), len(repoSetIDs)}, 739 {"substring no results and repo set", setAnd(helloworldSub), 0}, 740 } 741 742 for _, bb := range benchmarks { 743 b.Run(bb.name, func(b *testing.B) { 744 b.ReportAllocs() 745 746 for n := 0; n < b.N; n++ { 747 q := bb.q() 748 749 search(b, q, bb.wantFiles) 750 } 751 }) 752 } 753} 754 755func TestRawQuerySearch(t *testing.T) { 756 ss := newShardedSearcher(1) 757 758 var nextShardNum int 759 addShard := func(repo string, rawConfig map[string]string, docs ...index.Document) { 760 r := &zoekt.Repository{Name: repo} 761 r.RawConfig = rawConfig 762 b := testShardBuilder(t, r, docs...) 763 shard := searcherForTest(t, b) 764 ss.replace(map[string]zoekt.Searcher{fmt.Sprintf("key-%d", nextShardNum): shard}) 765 nextShardNum++ 766 } 767 addShard("public", map[string]string{"public": "1"}, index.Document{Name: "f1", Content: []byte("foo bar bas")}) 768 addShard("private_archived", map[string]string{"archived": "1"}, index.Document{Name: "f2", Content: []byte("foo bas")}) 769 addShard("public_fork", map[string]string{"public": "1", "fork": "1"}, index.Document{Name: "f3", Content: []byte("foo bar")}) 770 771 cases := []struct { 772 pattern string 773 flags query.RawConfig 774 wantRepos []string 775 wantFiles int 776 }{ 777 { 778 pattern: "bas", 779 flags: query.RcOnlyPublic, 780 wantRepos: []string{"public"}, 781 wantFiles: 1, 782 }, 783 { 784 pattern: "foo", 785 flags: query.RcOnlyPublic, 786 wantRepos: []string{"public", "public_fork"}, 787 wantFiles: 2, 788 }, 789 { 790 pattern: "foo", 791 flags: query.RcOnlyPublic | query.RcNoForks, 792 wantRepos: []string{"public"}, 793 wantFiles: 1, 794 }, 795 { 796 pattern: "bar", 797 flags: query.RcOnlyForks, 798 wantRepos: []string{"public_fork"}, 799 wantFiles: 1, 800 }, 801 { 802 pattern: "bas", 803 flags: query.RcNoArchived, 804 wantRepos: []string{"public"}, 805 wantFiles: 1, 806 }, 807 { 808 pattern: "foo", 809 flags: query.RcNoForks, 810 wantRepos: []string{"public", "private_archived"}, 811 wantFiles: 2, 812 }, 813 { 814 pattern: "bas", 815 flags: query.RcOnlyArchived, 816 wantRepos: []string{"private_archived"}, 817 wantFiles: 1, 818 }, 819 { 820 pattern: "foo", 821 flags: query.RcOnlyPrivate, 822 wantRepos: []string{"private_archived"}, 823 wantFiles: 1, 824 }, 825 { 826 pattern: "foo", 827 flags: query.RcOnlyPrivate | query.RcNoArchived, 828 wantRepos: []string{}, 829 wantFiles: 0, 830 }, 831 } 832 for _, c := range cases { 833 t.Run(fmt.Sprintf("pattern:%s", c.pattern), func(t *testing.T) { 834 q := query.NewAnd(&query.Substring{Pattern: c.pattern}, c.flags) 835 836 sr, err := ss.Search(context.Background(), q, &zoekt.SearchOptions{}) 837 if err != nil { 838 t.Fatal(err) 839 } 840 841 if got := len(sr.Files); got != c.wantFiles { 842 t.Fatalf("wanted %d, got %d", c.wantFiles, got) 843 } 844 845 if c.wantFiles == 0 { 846 return 847 } 848 849 gotRepos := make([]string, 0, len(sr.RepoURLs)) 850 for k := range sr.RepoURLs { 851 gotRepos = append(gotRepos, k) 852 } 853 sort.Strings(gotRepos) 854 sort.Strings(c.wantRepos) 855 if d := cmp.Diff(c.wantRepos, gotRepos); d != "" { 856 t.Fatalf("(-want, +got):\n%s", d) 857 } 858 }) 859 } 860} 861 862func TestPrioritySlice(t *testing.T) { 863 p := &prioritySlice{} 864 for step, oper := range []struct { 865 isAppend bool 866 value float64 867 expectedMax float64 868 }{ 869 {true, 1, 1}, 870 {true, 3, 3}, 871 {true, 2, 3}, 872 {false, 1, 3}, 873 {false, 3, 2}, 874 {false, 2, math.Inf(-1)}, 875 } { 876 if oper.isAppend { 877 p.append(oper.value) 878 } else { 879 p.remove(oper.value) 880 } 881 max := p.max() 882 if max != oper.expectedMax { 883 t.Errorf("%d: got %f, want %f", step, max, oper.expectedMax) 884 } 885 } 886} 887 888func TestSendByRepository(t *testing.T) { 889 wantStats := zoekt.Stats{} 890 wantStats.ShardsScanned = 1 891 892 // n1, n2, n3 are the number of file matches for each of the 3 repositories in this 893 // test. 894 f := func(n1, n2, n3 uint8) bool { 895 sr := createMockSearchResult(n1, n2, n3, wantStats) 896 897 mock := &mockSender{} 898 sendByRepository(sr, &zoekt.SearchOptions{}, mock) 899 900 if diff := cmp.Diff(wantStats, mock.stats); diff != "" { 901 t.Logf("-want,+got\n%s", diff) 902 return false 903 } 904 905 nonZero := 0 906 for _, l := range []uint8{n1, n2, n3} { 907 if l > 0 { 908 nonZero++ 909 } 910 } 911 if l := len(mock.files); l != nonZero { 912 t.Logf("wanted results from %d repositores, got %d", nonZero, l) 913 return false 914 } 915 916 gotTotal := 0 917 for _, fs := range mock.files { 918 gotTotal += len(fs) 919 } 920 wantTotal := int(n1) + int(n2) + int(n3) 921 if gotTotal != wantTotal { 922 t.Logf("wanted %d file matches, got %d", wantTotal, gotTotal) 923 return false 924 } 925 926 for _, fs := range mock.files { 927 if len(fs) == 0 { 928 t.Logf("got search result with 0 file matches after split") 929 return false 930 } 931 } 932 return true 933 } 934 935 if err := quick.Check(f, nil); err != nil { 936 t.Error(err) 937 } 938} 939 940type mockSender struct { 941 stats zoekt.Stats 942 files [][]zoekt.FileMatch 943} 944 945func (s *mockSender) Send(sr *zoekt.SearchResult) { 946 s.stats.Add(sr.Stats) 947 if len(sr.Files) == 0 { 948 return 949 } 950 s.files = append(s.files, sr.Files) 951} 952 953func createMockSearchResult(n1, n2, n3 uint8, stats zoekt.Stats) *zoekt.SearchResult { 954 sr := &zoekt.SearchResult{RepoURLs: make(map[string]string)} 955 for i, n := range []uint8{n1, n2, n3} { 956 if n == 0 { 957 continue 958 } 959 tmp := mkSearchResult(int(n), uint32(i)) 960 sr.Files = append(sr.Files, tmp.Files...) 961 for k := range tmp.RepoURLs { 962 sr.RepoURLs[k] = "" 963 } 964 } 965 sr.Stats = stats 966 return sr 967} 968 969func mkSearchResult(n int, repoID uint32) *zoekt.SearchResult { 970 if n == 0 { 971 return &zoekt.SearchResult{} 972 } 973 fm := make([]zoekt.FileMatch, 0, n) 974 for range n { 975 fm = append(fm, zoekt.FileMatch{Repository: fmt.Sprintf("repo%d", repoID), RepositoryID: repoID}) 976 } 977 978 return &zoekt.SearchResult{Files: fm, RepoURLs: map[string]string{fmt.Sprintf("repo%d", repoID): ""}} 979} 980 981func TestFileBasedSearch(t *testing.T) { 982 cases := []struct { 983 name string 984 testShardedSearch func(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch 985 }{ 986 {"Search", testShardedSearch}, 987 {"StreamSearch", testShardedStreamSearch}, 988 } 989 990 c1 := []byte("I love bananas without skin") 991 // -----------0123456789012345678901234567890123456789 992 c2 := []byte("In Dutch, ananas means pineapple") 993 // -----------0123456789012345678901234567890123456789 994 b := testShardBuilder(t, nil, 995 index.Document{Name: "f1", Content: c1}, 996 index.Document{Name: "f2", Content: c2}, 997 ) 998 999 for _, tt := range cases { 1000 for _, useDocumentRanks := range []bool{false, true} { 1001 t.Run(tt.name, func(t *testing.T) { 1002 matches := tt.testShardedSearch(t, &query.Substring{ 1003 CaseSensitive: false, 1004 Pattern: "ananas", 1005 }, b, useDocumentRanks) 1006 1007 if len(matches) != 2 { 1008 t.Fatalf("got %v, want 2 matches", matches) 1009 } 1010 if matches[0].FileName != "f2" || matches[1].FileName != "f1" { 1011 t.Fatalf("got %v, want matches {f1,f2}", matches) 1012 } 1013 if matches[0].LineMatches[0].LineFragments[0].Offset != 10 || matches[1].LineMatches[0].LineFragments[0].Offset != 8 { 1014 t.Fatalf("got %#v, want offsets 10,8", matches) 1015 } 1016 }) 1017 } 1018 } 1019} 1020 1021func TestWordBoundaryRanking(t *testing.T) { 1022 cases := []struct { 1023 name string 1024 testShardedSearch func(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch 1025 }{ 1026 {"Search", testShardedSearch}, 1027 {"StreamSearch", testShardedStreamSearch}, 1028 } 1029 1030 b := testShardBuilder(t, nil, 1031 index.Document{Name: "f1", Content: []byte("xbytex xbytex")}, 1032 index.Document{Name: "f2", Content: []byte("xbytex\nbytex\nbyte bla")}, 1033 // -----------------------------------------0123456 789012 34567890 1034 index.Document{Name: "f3", Content: []byte("xbytex ybytex")}) 1035 1036 for _, tt := range cases { 1037 for _, useDocumentRanks := range []bool{false, true} { 1038 t.Run(tt.name, func(t *testing.T) { 1039 files := tt.testShardedSearch(t, &query.Substring{Pattern: "byte"}, b, useDocumentRanks) 1040 1041 if len(files) != 3 { 1042 t.Fatalf("got %#v, want 3 files", files) 1043 } 1044 1045 file0 := files[0] 1046 if file0.FileName != "f2" || len(file0.LineMatches) != 3 { 1047 t.Fatalf("got file %s, num matches %d (%#v), want 3 matches in file f2", file0.FileName, len(file0.LineMatches), file0) 1048 } 1049 1050 if file0.LineMatches[0].LineFragments[0].Offset != 13 { 1051 t.Fatalf("got first match %#v, want full word match", files[0].LineMatches[0]) 1052 } 1053 if file0.LineMatches[1].LineFragments[0].Offset != 7 { 1054 t.Fatalf("got second match %#v, want partial word match", files[0].LineMatches[1]) 1055 } 1056 }) 1057 } 1058 } 1059} 1060 1061func TestAtomCountScore(t *testing.T) { 1062 cases := []struct { 1063 name string 1064 testShardedSearch func(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch 1065 }{ 1066 {"Search", testShardedSearch}, 1067 {"StreamSearch", testShardedStreamSearch}, 1068 } 1069 1070 b := testShardBuilder(t, 1071 &zoekt.Repository{ 1072 Branches: []zoekt.RepositoryBranch{ 1073 {Name: "branches", Version: "v1"}, 1074 {Name: "needle", Version: "v2"}, 1075 }, 1076 }, 1077 index.Document{Name: "f1", Content: []byte("needle the bla"), Branches: []string{"branches"}}, 1078 index.Document{Name: "needle-file-branch", Content: []byte("needle content"), Branches: []string{"needle"}}, 1079 index.Document{Name: "needle-file", Content: []byte("needle content"), Branches: []string{"branches"}}) 1080 1081 for _, tt := range cases { 1082 for _, useDocumentRanks := range []bool{false, true} { 1083 t.Run(tt.name, func(t *testing.T) { 1084 files := tt.testShardedSearch(t, 1085 query.NewOr( 1086 &query.Substring{Pattern: "needle"}, 1087 &query.Substring{Pattern: "needle", FileName: true}, 1088 &query.Branch{Pattern: "needle"}, 1089 ), b, useDocumentRanks) 1090 var got []string 1091 for _, f := range files { 1092 got = append(got, f.FileName) 1093 } 1094 want := []string{"needle-file-branch", "needle-file", "f1"} 1095 if !reflect.DeepEqual(got, want) { 1096 t.Errorf("got %v, want %v", got, want) 1097 } 1098 }) 1099 } 1100 } 1101} 1102 1103func TestUseBM25Scoring(t *testing.T) { 1104 b := testShardBuilder(t, 1105 &zoekt.Repository{}, 1106 index.Document{Name: "f1", Content: []byte("one two two three")}, 1107 index.Document{Name: "f2", Content: []byte("one two one two")}, 1108 index.Document{Name: "f3", Content: []byte("one three three three")}) 1109 1110 ss := newShardedSearcher(1) 1111 searcher := searcherForTest(t, b) 1112 ss.replace(map[string]zoekt.Searcher{"r1": searcher}) 1113 1114 q := query.NewOr( 1115 &query.Substring{Pattern: "one"}, 1116 &query.Substring{Pattern: "three"}) 1117 1118 opts := zoekt.SearchOptions{ 1119 UseBM25Scoring: true, 1120 } 1121 1122 results, err := ss.Search(context.Background(), q, &opts) 1123 if err != nil { 1124 t.Fatal(err) 1125 } 1126 1127 var got []string 1128 for _, f := range results.Files { 1129 got = append(got, f.FileName) 1130 } 1131 1132 want := []string{"f3", "f1", "f2"} 1133 if !reflect.DeepEqual(got, want) { 1134 t.Errorf("got %v, want %v", got, want) 1135 } 1136} 1137 1138func testShardedStreamSearch(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch { 1139 ss := newShardedSearcher(1) 1140 searcher := searcherForTest(t, ib) 1141 ss.replace(map[string]zoekt.Searcher{"r1": searcher}) 1142 1143 var files []zoekt.FileMatch 1144 sender := zoekt.SenderFunc(func(result *zoekt.SearchResult) { 1145 files = append(files, result.Files...) 1146 }) 1147 1148 opts := zoekt.SearchOptions{} 1149 if useDocumentRanks { 1150 opts.FlushWallTime = 10 * time.Millisecond 1151 } 1152 if err := ss.StreamSearch(context.Background(), q, &opts, sender); err != nil { 1153 t.Fatal(err) 1154 } 1155 return files 1156} 1157 1158func testShardedSearch(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch { 1159 ss := newShardedSearcher(1) 1160 searcher := searcherForTest(t, ib) 1161 ss.replace(map[string]zoekt.Searcher{"r1": searcher}) 1162 1163 opts := zoekt.SearchOptions{} 1164 if useDocumentRanks { 1165 opts.FlushWallTime = 50 * time.Millisecond 1166 } 1167 sres, _ := ss.Search(context.Background(), q, &opts) 1168 return sres.Files 1169} 1170 1171// Ensure we work on empty shard directories. 1172func TestNewDirectorySearcher_empty(t *testing.T) { 1173 ctx := context.Background() 1174 1175 test := func(t *testing.T, ss zoekt.Streamer) { 1176 res, err := ss.Search(ctx, &query.Const{Value: true}, nil) 1177 if err != nil { 1178 t.Fatal("Search non-nil error", err) 1179 } 1180 1181 if diff := cmp.Diff(&zoekt.SearchResult{}, res, cmpopts.IgnoreFields(zoekt.Stats{}, "Duration", "Wait"), cmpopts.EquateEmpty()); diff != "" { 1182 t.Fatalf("Search had non empty results (-want, +got):\n%s", diff) 1183 } 1184 1185 rl, err := ss.List(ctx, &query.Const{Value: true}, nil) 1186 if err != nil { 1187 t.Fatal("List non-nil error", err) 1188 } 1189 if diff := cmp.Diff(&zoekt.RepoList{}, rl, cmpopts.EquateEmpty()); diff != "" { 1190 t.Fatalf("List had non empty results (-want, +got):\n%s", diff) 1191 } 1192 } 1193 1194 dir := t.TempDir() 1195 t.Run("blocking", func(t *testing.T) { 1196 ss, err := NewDirectorySearcher(dir) 1197 if err != nil { 1198 t.Fatal(err) 1199 } 1200 t.Cleanup(ss.Close) 1201 1202 // We expect crashes to be empty as soon as NewDirectorySearcher returns 1203 // so we can validate straight away. 1204 test(t, ss) 1205 }) 1206 1207 t.Run("fast", func(t *testing.T) { 1208 ss, err := NewDirectorySearcherFast(dir) 1209 if err != nil { 1210 t.Fatal(err) 1211 } 1212 t.Cleanup(ss.Close) 1213 1214 deadline := testDeadline(t, 10*time.Second) 1215 1216 // Wait for scanning of directory to be done. We should be returning 1217 // non-zero crashes until then. 1218 waitForPredicate(deadline, 10*time.Millisecond, func() bool { 1219 res, err := ss.Search(ctx, &query.Const{Value: true}, nil) 1220 if err != nil { 1221 t.Fatal(err) 1222 } 1223 return res.Stats.Crashes == 0 1224 }) 1225 1226 test(t, ss) 1227 }) 1228} 1229 1230// testDeadline returns the deadline for t, but ensures it is no longer than 1231// maxTimeout away. 1232func testDeadline(t *testing.T, maxTimeout time.Duration) time.Time { 1233 deadline := time.Now().Add(maxTimeout) 1234 if d, ok := t.Deadline(); ok && d.Before(deadline) { 1235 // give 1s for us to do a final test run 1236 deadline = d.Add(-time.Second) 1237 } 1238 return deadline 1239} 1240 1241func waitForPredicate(deadline time.Time, tick time.Duration, pred func() bool) bool { 1242 for time.Now().Before(deadline) { 1243 if pred() { 1244 return true 1245 } 1246 1247 time.Sleep(tick) 1248 } 1249 1250 return pred() 1251}