diff --git a/search/eval.go b/search/eval.go index b1c342861..d84a03e99 100644 --- a/search/eval.go +++ b/search/eval.go @@ -4,6 +4,8 @@ import ( "context" "math" + "github.com/RoaringBitmap/roaring/v2" + "github.com/sourcegraph/zoekt" "github.com/sourcegraph/zoekt/internal/tenant" "github.com/sourcegraph/zoekt/internal/trace" @@ -127,7 +129,19 @@ func (s *typeRepoSearcher) List(ctx context.Context, q query.Q, opts *zoekt.List // It returns the number of shards that crashed while listing those // repositories. Their repositories are missing from the set, so callers must // report the crashes or the results look complete. +// +// A sub-query is listed only in the repositories q is limited to, see +// repoScope. Without that, a search of a few repositories lists the sub-query +// in every shard, and a repository outside the limit selects the repositories +// inside it that share its name. func (s *typeRepoSearcher) eval(ctx context.Context, tr *trace.Trace, q query.Q) (_ query.Q, crashes int, err error) { + // Most queries have no type:repo sub-query, so the scope is computed for + // the first one. + var ( + root = q + scope []query.Q + scoped bool + ) q = query.Map(q, func(q query.Q) query.Q { if err != nil { return nil @@ -140,8 +154,20 @@ func (s *typeRepoSearcher) eval(ctx context.Context, tr *trace.Trace, q query.Q) tr.LazyPrintf("evaluating sub-expression %s", rq) + if !scoped { + scope, scoped = repoScope(root), true + } + child := rq.Child + if len(scope) > 0 { + // One flat And, so the shards of other repositories are skipped + // before they are searched (selectRepoSet). + children := make([]query.Q, 0, len(scope)+1) + children = append(children, scope...) + child = &query.And{Children: append(children, child)} + } + var rl *zoekt.RepoList - rl, err = s.Streamer.List(ctx, rq.Child, nil) + rl, err = s.Streamer.List(ctx, child, nil) if err != nil { return nil } @@ -158,3 +184,35 @@ func (s *typeRepoSearcher) eval(ctx context.Context, tr *trace.Trace, q query.Q) }) return q, crashes, err } + +// repoScope returns the repository filters every result of q must match: +// each RepoIDs, RepoSet and BranchesRepos that is q or is reached from q +// through Ands only. Results come from the repositories matching all of them, +// so a type:repo sub-query anywhere in q only needs listing in those. +// +// A BranchesRepos is returned as the RepoIDs of its repositories: a type:repo +// sub-query selects a repository that matches on any of its branches, not +// only the branches being searched. +func repoScope(q query.Q) []query.Q { + switch s := q.(type) { + case *query.And: + var scope []query.Q + for _, c := range s.Children { + scope = append(scope, repoScope(c)...) + } + return scope + case *query.RepoIDs, *query.RepoSet: + return []query.Q{q} + case *query.BranchesRepos: + if len(s.List) == 1 { + // Shared, not copied: queries are not modified. + return []query.Q{&query.RepoIDs{Repos: s.List[0].Repos}} + } + bitmaps := make([]*roaring.Bitmap, 0, len(s.List)) + for _, br := range s.List { + bitmaps = append(bitmaps, br.Repos) + } + return []query.Q{&query.RepoIDs{Repos: roaring.FastOr(bitmaps...)}} + } + return nil +} diff --git a/search/eval_test.go b/search/eval_test.go index acdee6e77..8e8a30954 100644 --- a/search/eval_test.go +++ b/search/eval_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/RoaringBitmap/roaring/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -276,3 +277,136 @@ func TestSearchTypeRepoSchedulingClass(t *testing.T) { } assert.Equal(t, want, sched.classes) } + +// TestSearchTypeRepoScope checks that a type:repo sub-query only selects +// repositories the query is limited to. Repository names are not unique +// across tenants, and the sub-query is replaced by the names it matched. +func TestSearchTypeRepoScope(t *testing.T) { + ss := newShardedSearcher(2) + shards := map[string]zoekt.Searcher{ + // Two repositories share a name. Only the second has the needle. + "same-1": shardtest.Searcher(t, shardtest.Builder(t, &zoekt.Repository{ID: 1, Name: "same"}, + index.Document{Name: "f1", Content: []byte("haystack")})), + "same-2": shardtest.Searcher(t, shardtest.Builder(t, &zoekt.Repository{ID: 2, Name: "same"}, + index.Document{Name: "f2", Content: []byte("haystack with a needle")})), + // The needle is only on a branch that is not searched. + "branches": shardtest.Searcher(t, shardtest.Builder(t, &zoekt.Repository{ + ID: 3, + Name: "branches", + Branches: []zoekt.RepositoryBranch{{Name: "main", Version: "v1"}, {Name: "dev", Version: "v2"}}, + }, + index.Document{Name: "f3", Content: []byte("haystack"), Branches: []string{"main"}}, + index.Document{Name: "f4", Content: []byte("needle"), Branches: []string{"dev"}})), + } + ss.replace(shards) + searcher := &typeRepoSearcher{ss} + + hasNeedle := &query.Type{Type: query.TypeRepo, Child: &query.Substring{Pattern: "needle"}} + haystack := &query.Substring{Pattern: "haystack"} + + tests := []struct { + name string + q query.Q + want []string + }{{ + name: "repository with the needle", + q: query.NewAnd(query.NewRepoIDs(2), hasNeedle, haystack), + want: []string{"f2"}, + }, { + name: "repository sharing its name with one that has the needle", + q: query.NewAnd(query.NewRepoIDs(1), hasNeedle, haystack), + want: nil, + }, { + name: "negated", + q: query.NewAnd(query.NewRepoIDs(1), &query.Not{Child: hasNeedle}, haystack), + want: []string{"f1"}, + }, { + name: "limit in a nested And", + q: query.NewAnd(query.NewRepoIDs(1, 2, 3), query.NewAnd(query.NewRepoIDs(1), query.NewAnd(hasNeedle, haystack))), + want: nil, + }, { + name: "branches of the limit do not limit the sub-query", + q: query.NewAnd(query.NewSingleBranchesRepos("main", 3), hasNeedle, haystack), + want: []string{"f3"}, + }, { + name: "limit that is not required", + q: query.NewAnd(query.NewOr(query.NewRepoIDs(1), query.NewRepoIDs(3)), hasNeedle, haystack), + // Not limited: the first repository is selected by the name it shares. + want: []string{"f1", "f3"}, + }, { + name: "no limit", + q: query.NewAnd(hasNeedle, haystack), + want: []string{"f1", "f2", "f3"}, + }} + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res, err := searcher.Search(context.Background(), tc.q, &zoekt.SearchOptions{}) + require.NoError(t, err) + var got []string + for _, f := range res.Files { + got = append(got, f.FileName) + } + assert.ElementsMatch(t, tc.want, got) + }) + } + + t.Run("List", func(t *testing.T) { + rl, err := searcher.List(context.Background(), query.NewAnd(query.NewRepoIDs(1), hasNeedle), nil) + require.NoError(t, err) + assert.Empty(t, rl.Repos) + + rl, err = searcher.List(context.Background(), query.NewAnd(query.NewRepoIDs(2), hasNeedle), nil) + require.NoError(t, err) + require.Len(t, rl.Repos, 1) + assert.Equal(t, uint32(2), rl.Repos[0].Repository.ID) + }) +} + +func TestRepoScope(t *testing.T) { + sub := &query.Type{Type: query.TypeRepo, Child: &query.Substring{Pattern: "needle"}} + tests := []struct { + name string + q query.Q + want string + }{{ + name: "no filters", + q: query.NewAnd(sub, &query.Substring{Pattern: "haystack"}), + want: "[]", + }, { + name: "not an And", + q: sub, + want: "[]", + }, { + name: "filters in nested Ands", + q: query.NewAnd(query.NewRepoIDs(7), query.NewAnd(query.NewRepoSet("a"), sub)), + want: "[(repoids repoid={7}) (reposet a)]", + }, { + name: "one branch", + q: query.NewAnd(query.NewSingleBranchesRepos("HEAD", 7), sub), + want: "[(repoids repoid={7})]", + }, { + name: "branches are merged", + q: query.NewAnd(&query.BranchesRepos{List: []query.BranchRepos{ + {Branch: "HEAD", Repos: roaring.BitmapOf(1, 2)}, + {Branch: "dev", Repos: roaring.BitmapOf(2, 3)}, + }}, sub), + want: "[(repoids count:3)]", + }, { + name: "no branches", + q: query.NewAnd(&query.BranchesRepos{}, sub), + want: "[(repoids repoid={})]", + }, { + name: "filters that are not required", + q: query.NewAnd( + query.NewOr(query.NewRepoIDs(1), query.NewRepoIDs(2)), + &query.Not{Child: query.NewRepoIDs(3)}, + &query.Type{Type: query.TypeRepo, Child: query.NewRepoIDs(4)}, + sub), + want: "[]", + }} + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, fmt.Sprint(repoScope(tc.q))) + }) + } +}