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