fork of https://github.com/sourcegraph/zoekt
1package e2e
2
3import (
4 "bytes"
5 "context"
6 "flag"
7 "fmt"
8 "io"
9 "net/url"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/google/go-cmp/cmp"
18 "github.com/sourcegraph/zoekt"
19 "github.com/sourcegraph/zoekt/build"
20 "github.com/sourcegraph/zoekt/internal/archive"
21 "github.com/sourcegraph/zoekt/query"
22 "github.com/sourcegraph/zoekt/shards"
23)
24
25var update = flag.Bool("update", false, "update golden file")
26
27var useShardCache = flag.Bool("shard_cache", false, "cache computed shards for faster test runs")
28
29// debugScore can be set to include much more output. Do not commit the
30// updated golden files, this is purely used for debugging in a local
31// environment.
32var debugScore = flag.Bool("debug_score", false, "include debug output in golden files.")
33
34func TestRanking(t *testing.T) {
35 if testing.Short() {
36 t.Skip("skipping due to short flag")
37 }
38
39 requireCTags(t)
40
41 archiveURLs := []string{
42 "https://github.com/sourcegraph/sourcegraph/tree/v5.2.2",
43 "https://github.com/golang/go/tree/go1.21.4",
44 "https://github.com/sourcegraph/cody/tree/vscode-v0.14.5",
45 // The commit before ranking e2e tests were added to avoid matching
46 // content inside our golden files.
47 "https://github.com/sourcegraph/zoekt/commit/ef907c2371176aa3f97713d5bf182983ef090c6a",
48 }
49 q := func(query, target string) rankingQuery {
50 return rankingQuery{Query: query, Target: target}
51 }
52 queries := []rankingQuery{
53 // golang/go
54 q("test server", "github.com/golang/go/src/net/http/httptest/server.go"),
55 q("bytes buffer", "github.com/golang/go/src/bytes/buffer.go"),
56 q("bufio buffer", "github.com/golang/go/src/bufio/scan.go"),
57 q("time compare\\(", "github.com/golang/go/src/time/time.go"),
58
59 // sourcegraph/sourcegraph
60 q("graphql type User", "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/schema.graphql"),
61 q("Get database/user", "github.com/sourcegraph/sourcegraph/internal/database/users.go"),
62 q("InternalDoer", "github.com/sourcegraph/sourcegraph/internal/httpcli/client.go"),
63 q("Repository metadata Write rbac", "github.com/sourcegraph/sourcegraph/internal/rbac/constants.go"), // unsure if this is the best doc?
64
65 // cody
66 q("generate unit test", "github.com/sourcegraph/cody/lib/shared/src/chat/recipes/generate-test.ts"),
67 q("r:cody sourcegraph url", "github.com/sourcegraph/cody/lib/shared/src/sourcegraph-api/graphql/client.ts"),
68
69 // zoekt
70 q("zoekt searcher", "github.com/sourcegraph/zoekt/api.go"),
71
72 // exact phrases
73 q("assets are not configured for this binary", "github.com/sourcegraph/sourcegraph/ui/assets/assets.go"),
74 q("sourcegraph/server docker image build", "github.com/sourcegraph/sourcegraph/dev/tools.go"),
75
76 // symbols split up
77 q("bufio flush writer", "github.com/golang/go/src/net/http/transfer.go"), // bufioFlushWriter
78 q("coverage data writer", "github.com/golang/go/src/internal/coverage/encodecounter/encode.go"), // CoverageDataWriter
79 }
80
81 var indexDir string
82 if *useShardCache {
83 t.Logf("reusing index dir to speed up testing. If you have unexpected results remove %s", shardCache)
84 indexDir = shardCache
85 } else {
86 indexDir = t.TempDir()
87 }
88
89 for _, u := range archiveURLs {
90 if err := indexURL(indexDir, u); err != nil {
91 t.Fatal(err)
92 }
93 }
94
95 ss, err := shards.NewDirectorySearcher(indexDir)
96 if err != nil {
97 t.Fatalf("NewDirectorySearcher(%s): %v", indexDir, err)
98 }
99 defer ss.Close()
100
101 var ranks []int
102 for _, rq := range queries {
103 // normalise queryStr for writing to fs
104 name := strings.Map(func(r rune) rune {
105 if strings.ContainsRune(" :", r) {
106 return '_'
107 }
108 if '0' <= r && r <= '9' ||
109 'a' <= r && r <= 'z' ||
110 'A' <= r && r <= 'Z' {
111 return r
112 }
113 return -1
114 }, rq.Query)
115
116 t.Run(name, func(t *testing.T) {
117 q, err := query.Parse(rq.Query)
118 if err != nil {
119 t.Fatal(err)
120 }
121
122 // q is marshalled as part of the test, so avoid our rewrites for
123 // ranking.
124 qSearch := query.ExpirementalPhraseBoost(q, rq.Query, query.ExperimentalPhraseBoostOptions{})
125
126 sOpts := zoekt.SearchOptions{
127 // Use the same options sourcegraph has by default
128 ChunkMatches: true,
129 MaxWallTime: 20 * time.Second,
130 ShardMaxMatchCount: 10_000 * 10,
131 TotalMaxMatchCount: 100_000 * 10,
132 MaxDocDisplayCount: 500,
133
134 DebugScore: *debugScore,
135 }
136 result, err := ss.Search(context.Background(), qSearch, &sOpts)
137 if err != nil {
138 t.Fatal(err)
139 }
140
141 ranks = append(ranks, targetRank(rq, result.Files))
142
143 var gotBuf bytes.Buffer
144 marshalMatches(&gotBuf, rq, q, result.Files)
145 assertGolden(t, name, gotBuf.Bytes())
146 })
147 }
148
149 t.Run("rank_stats", func(t *testing.T) {
150 if len(ranks) != len(queries) {
151 t.Skip("not computing rank stats since not all query cases ran")
152 }
153
154 var gotBuf bytes.Buffer
155 printf := func(format string, a ...any) {
156 _, _ = fmt.Fprintf(&gotBuf, format, a...)
157 }
158
159 printf("queries: %d\n", len(ranks))
160
161 for _, recallThreshold := range []int{1, 5} {
162 count := 0
163 for _, rank := range ranks {
164 if rank <= recallThreshold && rank > 0 {
165 count++
166 }
167 }
168 countp := float64(count) * 100 / float64(len(ranks))
169 printf("recall@%d: %d (%.0f%%)\n", recallThreshold, count, countp)
170 }
171
172 // Mean reciprocal rank
173 mrr := float64(0)
174 for _, rank := range ranks {
175 if rank > 0 {
176 mrr += 1 / float64(rank)
177 }
178 }
179 mrr /= float64(len(ranks))
180 printf("mrr: %f\n", mrr)
181
182 assertGolden(t, "rank_stats", gotBuf.Bytes())
183 })
184}
185
186func assertGolden(t *testing.T, name string, got []byte) {
187 t.Helper()
188
189 wantPath := filepath.Join("testdata", name+".txt")
190 if *update {
191 if err := os.WriteFile(wantPath, got, 0o600); err != nil {
192 t.Fatal(err)
193 }
194 }
195 want, err := os.ReadFile(wantPath)
196 if err != nil {
197 t.Fatal(err)
198 }
199
200 if d := cmp.Diff(string(want), string(got)); d != "" {
201 t.Fatalf("unexpected (-want, +got):\n%s", d)
202 }
203}
204
205type rankingQuery struct {
206 Query string
207 Target string
208}
209
210var (
211 tarballCache = "/tmp/zoekt-test-ranking-tarballs-" + os.Getenv("USER")
212 shardCache = "/tmp/zoekt-test-ranking-shards-" + os.Getenv("USER")
213)
214
215func indexURL(indexDir, u string) error {
216 if err := os.MkdirAll(tarballCache, 0o700); err != nil {
217 return err
218 }
219
220 opts := archive.Options{
221 Archive: u,
222 Incremental: true,
223 }
224 opts.SetDefaults() // sets metadata like Name and the codeload URL
225 u = opts.Archive
226
227 // if opts.Commit is set but opts.Branch is not, then we just need to give
228 // the commit a name for testing.
229 if opts.Commit != "" && opts.Branch == "" {
230 opts.Branch = "test"
231 }
232
233 // update Archive location to cached location
234 cacheBase := fmt.Sprintf("%s-%s%s.tar.gz", url.QueryEscape(opts.Name), opts.Branch, opts.Commit) // assume .tar.gz
235 path := filepath.Join(tarballCache, cacheBase)
236 opts.Archive = path
237
238 if _, err := os.Stat(path); os.IsNotExist(err) {
239 if err := download(u, path); err != nil {
240 return err
241 }
242 }
243
244 // TODO scip
245 // languageMap := make(ctags.LanguageMap)
246 // for _, lang := range []string{"kotlin", "rust", "ruby", "go", "python", "javascript", "c_sharp", "scala", "typescript", "zig"} {
247 // languageMap[lang] = ctags.ScipCTags
248 // }
249
250 err := archive.Index(opts, build.Options{
251 IndexDir: indexDir,
252 CTagsMustSucceed: true,
253 })
254 if err != nil {
255 return fmt.Errorf("failed to index %s: %w", opts.Archive, err)
256 }
257
258 return nil
259}
260
261func download(url, dst string) error {
262 tmpPath := dst + ".part"
263
264 rc, err := archive.OpenReader(url)
265 if err != nil {
266 return err
267 }
268 defer rc.Close()
269
270 f, err := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
271 if err != nil {
272 return err
273 }
274 defer f.Close()
275
276 _, err = io.Copy(f, rc)
277 if err != nil {
278 return err
279 }
280
281 err = f.Close()
282 if err != nil {
283 return err
284 }
285
286 return os.Rename(tmpPath, dst)
287}
288
289const (
290 chunkMatchesPerFile = 3
291 fileMatchesPerSearch = 6
292)
293
294func docName(f zoekt.FileMatch) string {
295 return f.Repository + "/" + f.FileName
296}
297
298func marshalMatches(w io.Writer, rq rankingQuery, q query.Q, files []zoekt.FileMatch) {
299 _, _ = fmt.Fprintf(w, "queryString: %s\n", rq.Query)
300 _, _ = fmt.Fprintf(w, "query: %s\n", q)
301 _, _ = fmt.Fprintf(w, "targetRank: %d\n\n", targetRank(rq, files))
302
303 files, hiddenFiles := splitAtIndex(files, fileMatchesPerSearch)
304 for _, f := range files {
305 doc := docName(f)
306 if doc == rq.Target {
307 doc = "**" + doc + "**"
308 }
309 _, _ = fmt.Fprintf(w, "%s%s\n", doc, addTabIfNonEmpty(f.Debug))
310
311 chunks, hidden := splitAtIndex(f.ChunkMatches, chunkMatchesPerFile)
312
313 for _, m := range chunks {
314 _, _ = fmt.Fprintf(w, "%d:%s%s\n", m.ContentStart.LineNumber, strings.TrimRight(string(m.Content), "\n"), addTabIfNonEmpty(m.DebugScore))
315 }
316
317 if len(hidden) > 0 {
318 _, _ = fmt.Fprintf(w, "hidden %d more line matches\n", len(hidden))
319 }
320 _, _ = fmt.Fprintln(w)
321 }
322
323 if len(hiddenFiles) > 0 {
324 fmt.Fprintf(w, "hidden %d more file matches\n", len(hiddenFiles))
325 }
326}
327
328func targetRank(rq rankingQuery, files []zoekt.FileMatch) int {
329 for i, f := range files {
330 if docName(f) == rq.Target {
331 return i + 1
332 }
333 }
334 return -1
335}
336
337func splitAtIndex[E any](s []E, idx int) ([]E, []E) {
338 if idx < len(s) {
339 return s[:idx], s[idx:]
340 }
341 return s, nil
342}
343
344func addTabIfNonEmpty(s string) string {
345 if s != "" {
346 return "\t" + s
347 }
348 return s
349}
350
351func requireCTags(tb testing.TB) {
352 tb.Helper()
353
354 if os.Getenv("CTAGS_COMMAND") != "" {
355 return
356 }
357 if _, err := exec.LookPath("universal-ctags"); err == nil {
358 return
359 }
360
361 // On CI we require ctags to be available. Otherwise we skip
362 if os.Getenv("CI") != "" {
363 tb.Fatal("universal-ctags is missing")
364 } else {
365 tb.Skip("universal-ctags is missing")
366 }
367}