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

Configure Feed

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

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