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-public-snapshot/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-public-snapshot/cmd/frontend/graphqlbackend/schema.graphql"), 61 q("Get database/user", "github.com/sourcegraph/sourcegraph-public-snapshot/internal/database/users.go"), 62 q("InternalDoer", "github.com/sourcegraph/sourcegraph-public-snapshot/internal/httpcli/client.go"), 63 q("Repository metadata Write rbac", "github.com/sourcegraph/sourcegraph-public-snapshot/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-public-snapshot/ui/assets/assets.go"), 74 q("sourcegraph/server docker image build", "github.com/sourcegraph/sourcegraph-public-snapshot/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 sOpts := zoekt.SearchOptions{ 123 // Use the same options sourcegraph has by default 124 ChunkMatches: true, 125 MaxWallTime: 20 * time.Second, 126 ShardMaxMatchCount: 10_000 * 10, 127 TotalMaxMatchCount: 100_000 * 10, 128 MaxDocDisplayCount: 500, 129 130 DebugScore: *debugScore, 131 } 132 result, err := ss.Search(context.Background(), q, &sOpts) 133 if err != nil { 134 t.Fatal(err) 135 } 136 137 ranks = append(ranks, targetRank(rq, result.Files)) 138 139 var gotBuf bytes.Buffer 140 marshalMatches(&gotBuf, rq, q, result.Files) 141 assertGolden(t, name, gotBuf.Bytes()) 142 }) 143 } 144 145 t.Run("rank_stats", func(t *testing.T) { 146 if len(ranks) != len(queries) { 147 t.Skip("not computing rank stats since not all query cases ran") 148 } 149 150 var gotBuf bytes.Buffer 151 printf := func(format string, a ...any) { 152 _, _ = fmt.Fprintf(&gotBuf, format, a...) 153 } 154 155 printf("queries: %d\n", len(ranks)) 156 157 for _, recallThreshold := range []int{1, 5} { 158 count := 0 159 for _, rank := range ranks { 160 if rank <= recallThreshold && rank > 0 { 161 count++ 162 } 163 } 164 countp := float64(count) * 100 / float64(len(ranks)) 165 printf("recall@%d: %d (%.0f%%)\n", recallThreshold, count, countp) 166 } 167 168 // Mean reciprocal rank 169 mrr := float64(0) 170 for _, rank := range ranks { 171 if rank > 0 { 172 mrr += 1 / float64(rank) 173 } 174 } 175 mrr /= float64(len(ranks)) 176 printf("mrr: %f\n", mrr) 177 178 assertGolden(t, "rank_stats", gotBuf.Bytes()) 179 }) 180} 181 182func assertGolden(t *testing.T, name string, got []byte) { 183 t.Helper() 184 185 wantPath := filepath.Join("testdata", name+".txt") 186 if *update { 187 if err := os.WriteFile(wantPath, got, 0o600); err != nil { 188 t.Fatal(err) 189 } 190 } 191 want, err := os.ReadFile(wantPath) 192 if err != nil { 193 t.Fatal(err) 194 } 195 196 if d := cmp.Diff(string(want), string(got)); d != "" { 197 t.Fatalf("unexpected (-want, +got):\n%s", d) 198 } 199} 200 201type rankingQuery struct { 202 Query string 203 Target string 204} 205 206var ( 207 tarballCache = "/tmp/zoekt-test-ranking-tarballs-" + os.Getenv("USER") 208 shardCache = "/tmp/zoekt-test-ranking-shards-" + os.Getenv("USER") 209) 210 211func indexURL(indexDir, u string) error { 212 if err := os.MkdirAll(tarballCache, 0o700); err != nil { 213 return err 214 } 215 216 opts := archive.Options{ 217 Archive: u, 218 Incremental: true, 219 } 220 opts.SetDefaults() // sets metadata like Name and the codeload URL 221 u = opts.Archive 222 223 // if opts.Commit is set but opts.Branch is not, then we just need to give 224 // the commit a name for testing. 225 if opts.Commit != "" && opts.Branch == "" { 226 opts.Branch = "test" 227 } 228 229 // update Archive location to cached location 230 cacheBase := fmt.Sprintf("%s-%s%s.tar.gz", url.QueryEscape(opts.Name), opts.Branch, opts.Commit) // assume .tar.gz 231 path := filepath.Join(tarballCache, cacheBase) 232 opts.Archive = path 233 234 if _, err := os.Stat(path); os.IsNotExist(err) { 235 if err := download(u, path); err != nil { 236 return err 237 } 238 } 239 240 // TODO scip 241 // languageMap := make(ctags.LanguageMap) 242 // for _, lang := range []string{"kotlin", "rust", "ruby", "go", "python", "javascript", "c_sharp", "scala", "typescript", "zig"} { 243 // languageMap[lang] = ctags.ScipCTags 244 // } 245 246 err := archive.Index(opts, build.Options{ 247 IndexDir: indexDir, 248 CTagsMustSucceed: true, 249 }) 250 if err != nil { 251 return fmt.Errorf("failed to index %s: %w", opts.Archive, err) 252 } 253 254 return nil 255} 256 257func download(url, dst string) error { 258 tmpPath := dst + ".part" 259 260 rc, err := archive.OpenReader(url) 261 if err != nil { 262 return err 263 } 264 defer rc.Close() 265 266 f, err := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) 267 if err != nil { 268 return err 269 } 270 defer f.Close() 271 272 _, err = io.Copy(f, rc) 273 if err != nil { 274 return err 275 } 276 277 err = f.Close() 278 if err != nil { 279 return err 280 } 281 282 return os.Rename(tmpPath, dst) 283} 284 285const ( 286 chunkMatchesPerFile = 3 287 fileMatchesPerSearch = 6 288) 289 290func docName(f zoekt.FileMatch) string { 291 return f.Repository + "/" + f.FileName 292} 293 294func marshalMatches(w io.Writer, rq rankingQuery, q query.Q, files []zoekt.FileMatch) { 295 _, _ = fmt.Fprintf(w, "queryString: %s\n", rq.Query) 296 _, _ = fmt.Fprintf(w, "query: %s\n", q) 297 _, _ = fmt.Fprintf(w, "targetRank: %d\n\n", targetRank(rq, files)) 298 299 files, hiddenFiles := splitAtIndex(files, fileMatchesPerSearch) 300 for _, f := range files { 301 doc := docName(f) 302 if doc == rq.Target { 303 doc = "**" + doc + "**" 304 } 305 _, _ = fmt.Fprintf(w, "%s%s\n", doc, addTabIfNonEmpty(f.Debug)) 306 307 chunks, hidden := splitAtIndex(f.ChunkMatches, chunkMatchesPerFile) 308 309 for _, m := range chunks { 310 _, _ = fmt.Fprintf(w, "%d:%s%s\n", m.ContentStart.LineNumber, strings.TrimRight(string(m.Content), "\n"), addTabIfNonEmpty(m.DebugScore)) 311 } 312 313 if len(hidden) > 0 { 314 _, _ = fmt.Fprintf(w, "hidden %d more line matches\n", len(hidden)) 315 } 316 _, _ = fmt.Fprintln(w) 317 } 318 319 if len(hiddenFiles) > 0 { 320 fmt.Fprintf(w, "hidden %d more file matches\n", len(hiddenFiles)) 321 } 322} 323 324func targetRank(rq rankingQuery, files []zoekt.FileMatch) int { 325 for i, f := range files { 326 if docName(f) == rq.Target { 327 return i + 1 328 } 329 } 330 return -1 331} 332 333func splitAtIndex[E any](s []E, idx int) ([]E, []E) { 334 if idx < len(s) { 335 return s[:idx], s[idx:] 336 } 337 return s, nil 338} 339 340func addTabIfNonEmpty(s string) string { 341 if s != "" { 342 return "\t" + s 343 } 344 return s 345} 346 347func requireCTags(tb testing.TB) { 348 tb.Helper() 349 350 if os.Getenv("CTAGS_COMMAND") != "" { 351 return 352 } 353 if _, err := exec.LookPath("universal-ctags"); err == nil { 354 return 355 } 356 357 // On CI we require ctags to be available. Otherwise we skip 358 if os.Getenv("CI") != "" { 359 tb.Fatal("universal-ctags is missing") 360 } else { 361 tb.Skip("universal-ctags is missing") 362 } 363}