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 index 16 17import ( 18 "bytes" 19 "fmt" 20 "math" 21 "strings" 22 23 "github.com/sourcegraph/zoekt" 24 "github.com/sourcegraph/zoekt/internal/ctags" 25) 26 27const ( 28 ScoreOffset = 10_000_000 29) 30 31type chunkScore struct { 32 score float64 33 debugScore string 34 bestLine int 35} 36 37// scoreChunk calculates the score for each line in the chunk based on its candidate matches, and returns the score of 38// the best-scoring line, along with its line number. 39// Invariant: there should be at least one input candidate, len(ms) > 0. 40func (p *contentProvider) scoreChunk(ms []*candidateMatch, language string, opts *zoekt.SearchOptions) (chunkScore, []*zoekt.Symbol) { 41 nl := p.newlines() 42 43 var bestScore lineScore 44 bestLine := 0 45 var symbolInfo []*zoekt.Symbol 46 47 start := 0 48 currentLine := -1 49 for i, m := range ms { 50 lineNumber := -1 51 if !m.fileName { 52 lineNumber = nl.atOffset(m.byteOffset) 53 } 54 55 // If this match represents a new line, then score the previous line and update 'start'. 56 if i != 0 && lineNumber != currentLine { 57 score, si := p.scoreLine(ms[start:i], language, currentLine, opts) 58 symbolInfo = append(symbolInfo, si...) 59 if score.score > bestScore.score { 60 bestScore = score 61 bestLine = currentLine 62 } 63 start = i 64 } 65 currentLine = lineNumber 66 } 67 68 // Make sure to score the last line 69 line, si := p.scoreLine(ms[start:], language, currentLine, opts) 70 symbolInfo = append(symbolInfo, si...) 71 if line.score > bestScore.score { 72 bestScore = line 73 bestLine = currentLine 74 } 75 76 cs := chunkScore{ 77 score: bestScore.score, 78 bestLine: bestLine, 79 } 80 if opts.DebugScore { 81 cs.debugScore = fmt.Sprintf("%s, (line: %d)", bestScore.debugScore, bestLine) 82 } 83 return cs, symbolInfo 84} 85 86type lineScore struct { 87 score float64 88 debugScore string 89} 90 91// scoreLine calculates a score for the line based on its candidate matches. 92// Invariants: 93// - All candidate matches are assumed to come from the same line in the content. 94// - If this line represents a filename, then lineNumber must be -1. 95// - There should be at least one input candidate, len(ms) > 0. 96func (p *contentProvider) scoreLine(ms []*candidateMatch, language string, lineNumber int, opts *zoekt.SearchOptions) (lineScore, []*zoekt.Symbol) { 97 if opts.UseBM25Scoring { 98 score, symbolInfo := p.scoreLineBM25(ms, lineNumber) 99 ls := lineScore{score: score} 100 if opts.DebugScore { 101 ls.debugScore = fmt.Sprintf("tfScore:%.2f, ", score) 102 } 103 return ls, symbolInfo 104 } 105 106 score := 0.0 107 what := "" 108 addScore := func(w string, s float64) { 109 if s != 0 && opts.DebugScore { 110 what += fmt.Sprintf("%s:%.2f, ", w, s) 111 } 112 score += s 113 } 114 115 filename := p.data(true) 116 var symbolInfo []*zoekt.Symbol 117 118 var bestScore lineScore 119 for i, m := range ms { 120 data := p.data(m.fileName) 121 122 endOffset := m.byteOffset + m.byteMatchSz 123 startBoundary := m.byteOffset < uint32(len(data)) && (m.byteOffset == 0 || byteClass(data[m.byteOffset-1]) != byteClass(data[m.byteOffset])) 124 endBoundary := endOffset > 0 && (endOffset == uint32(len(data)) || byteClass(data[endOffset-1]) != byteClass(data[endOffset])) 125 126 score = 0 127 what = "" 128 129 if startBoundary && endBoundary { 130 addScore("WordMatch", scoreWordMatch) 131 } else if startBoundary || endBoundary { 132 addScore("PartialWordMatch", scorePartialWordMatch) 133 } 134 135 if m.fileName { 136 sep := bytes.LastIndexByte(data, '/') 137 startMatch := int(m.byteOffset) == sep+1 138 endMatch := endOffset == uint32(len(data)) 139 if startMatch && endMatch { 140 addScore("Base", scoreBase) 141 } else if startMatch || endMatch { 142 addScore("EdgeBase", (scoreBase+scorePartialBase)/2) 143 } else if sep < int(m.byteOffset) { 144 addScore("InnerBase", scorePartialBase) 145 } 146 } else if sec, si, ok := p.findSymbol(m); ok { 147 startMatch := sec.Start == m.byteOffset 148 endMatch := sec.End == endOffset 149 if startMatch && endMatch { 150 addScore("Symbol", scoreSymbol) 151 } else if startMatch || endMatch { 152 addScore("EdgeSymbol", (scoreSymbol+scorePartialSymbol)/2) 153 } else { 154 addScore("OverlapSymbol", scorePartialSymbol) 155 } 156 157 // Score based on symbol data 158 if si != nil { 159 symbolKind := ctags.ParseSymbolKind(si.Kind) 160 sym := sectionSlice(data, sec) 161 162 addScore(fmt.Sprintf("kind:%s:%s", language, si.Kind), scoreSymbolKind(language, filename, sym, symbolKind)) 163 164 // This is from a symbol tree, so we need to store the symbol 165 // information. 166 if m.symbol { 167 if symbolInfo == nil { 168 symbolInfo = make([]*zoekt.Symbol, len(ms)) 169 } 170 // findSymbols does not hydrate in Sym. So we need to store it. 171 si.Sym = string(sym) 172 symbolInfo[i] = si 173 } 174 } 175 } 176 177 // scoreWeight != 1 means it affects score 178 if !epsilonEqualsOne(m.scoreWeight) { 179 score = score * m.scoreWeight 180 if opts.DebugScore { 181 what += fmt.Sprintf("boost:%.2f, ", m.scoreWeight) 182 } 183 } 184 185 if score > bestScore.score { 186 bestScore.score = score 187 bestScore.debugScore = what 188 } 189 } 190 191 if opts.DebugScore { 192 bestScore.debugScore = fmt.Sprintf("score:%.2f <- %s", bestScore.score, strings.TrimSuffix(bestScore.debugScore, ", ")) 193 } 194 195 return bestScore, symbolInfo 196} 197 198// scoreLineBM25 computes the score of a line according to BM25, the most common scoring algorithm for text search: 199// https://en.wikipedia.org/wiki/Okapi_BM25. Compared to the standard scoreLine algorithm, this score rewards multiple 200// term matches on a line. 201// Notes: 202// - This BM25 calculation skips inverse document frequency (idf) to keep the implementation simple. 203// - It uses the same calculateTermFrequency method as BM25 file scoring, which boosts filename and symbol matches. 204func (p *contentProvider) scoreLineBM25(ms []*candidateMatch, lineNumber int) (float64, []*zoekt.Symbol) { 205 // If this is a filename, then don't compute BM25. The score would not be comparable to line scores. 206 if lineNumber < 0 { 207 return 0, nil 208 } 209 210 // Use standard parameter defaults used in Lucene (https://lucene.apache.org/core/10_1_0/core/org/apache/lucene/search/similarities/BM25Similarity.html) 211 k, b := 1.2, 0.75 212 213 // Calculate the length ratio of this line. As a heuristic, we assume an average line length of 100 characters. 214 // Usually the calculation would be based on terms, but using bytes should work fine, as we're just computing a ratio. 215 nl := p.newlines() 216 lineLength := nl.lineStart(lineNumber+1) - nl.lineStart(lineNumber) 217 L := float64(lineLength) / 100.0 218 219 score := 0.0 220 tfs := p.calculateTermFrequency(ms) 221 for _, f := range tfs { 222 score += tfScore(k, b, L, f) 223 } 224 225 // Check if any index comes from a symbol match tree, and if so hydrate in symbol information 226 var symbolInfo []*zoekt.Symbol 227 for _, m := range ms { 228 if m.symbol { 229 if sec, si, ok := p.findSymbol(m); ok && si != nil { 230 // findSymbols does not hydrate in Sym. So we need to store it. 231 sym := sectionSlice(p.data(false), sec) 232 si.Sym = string(sym) 233 symbolInfo = append(symbolInfo, si) 234 } 235 } 236 } 237 return score, symbolInfo 238} 239 240// tfScore is the term frequency score for BM25. 241func tfScore(k float64, b float64, L float64, f int) float64 { 242 return ((k + 1.0) * float64(f)) / (k*(1.0-b+b*L) + float64(f)) 243} 244 245// calculateTermFrequency computes the term frequency for the file match. 246// Notes: 247// - Filename matches count more than content matches. This mimics a common text search strategy to 'boost' matches on document titles. 248// - Symbol matches also count more than content matches, to reward matches on symbol definitions. 249func (p *contentProvider) calculateTermFrequency(cands []*candidateMatch) map[string]int { 250 // Treat each candidate match as a term and compute the frequencies. For now, ignore case sensitivity and 251 // ignore whether the index is a word boundary. 252 termFreqs := map[string]int{} 253 for _, m := range cands { 254 term := string(m.substrLowered) 255 if m.fileName || p.matchesSymbol(m) { 256 termFreqs[term] += 5 257 } else { 258 termFreqs[term]++ 259 } 260 } 261 262 return termFreqs 263} 264 265// scoreFile computes a score for the file match using various scoring signals, like 266// whether there's an exact match on a symbol, the number of query clauses that matched, etc. 267func (d *indexData) scoreFile(fileMatch *zoekt.FileMatch, doc uint32, mt matchTree, known map[matchTree]bool, opts *zoekt.SearchOptions) { 268 atomMatchCount := 0 269 visitMatchAtoms(mt, known, func(mt matchTree) { 270 atomMatchCount++ 271 }) 272 273 addScore := func(what string, computed float64) { 274 fileMatch.AddScore(what, computed, -1, opts.DebugScore) 275 } 276 277 // atom-count boosts files with matches from more than 1 atom. The 278 // maximum boost is scoreFactorAtomMatch. 279 if atomMatchCount > 0 { 280 fileMatch.AddScore("atom", (1.0-1.0/float64(atomMatchCount))*scoreFactorAtomMatch, float64(atomMatchCount), opts.DebugScore) 281 } 282 283 maxFileScore := 0.0 284 for i := range fileMatch.LineMatches { 285 if maxFileScore < fileMatch.LineMatches[i].Score { 286 maxFileScore = fileMatch.LineMatches[i].Score 287 } 288 289 // Order by ordering in file. 290 fileMatch.LineMatches[i].Score += scoreLineOrderFactor * (1.0 - (float64(i) / float64(len(fileMatch.LineMatches)))) 291 } 292 293 for i := range fileMatch.ChunkMatches { 294 if maxFileScore < fileMatch.ChunkMatches[i].Score { 295 maxFileScore = fileMatch.ChunkMatches[i].Score 296 } 297 298 // Order by ordering in file. 299 fileMatch.ChunkMatches[i].Score += scoreLineOrderFactor * (1.0 - (float64(i) / float64(len(fileMatch.ChunkMatches)))) 300 } 301 302 // Maintain ordering of input files. This 303 // strictly dominates the in-file ordering of 304 // the matches. 305 addScore("fragment", maxFileScore) 306 307 // Add tiebreakers 308 // 309 // ScoreOffset shifts the score 7 digits to the left. 310 fileMatch.Score = math.Trunc(fileMatch.Score) * ScoreOffset 311 312 md := d.repoMetaData[d.repos[doc]] 313 314 // md.Rank lies in the range [0, 65535]. Hence, we have to allocate 5 digits for 315 // the rank. The scoreRepoRankFactor shifts the rank score 2 digits to the left, 316 // reserving digits 3-7 for the repo rank. 317 addScore("repo-rank", scoreRepoRankFactor*float64(md.Rank)) 318 319 // digits 1-2 and the decimals are reserved for the doc order. Doc order 320 // (without the scaling factor) lies in the range [0, 1]. The upper bound is 321 // achieved for matches in the first document of a shard. 322 addScore("doc-order", scoreFileOrderFactor*(1.0-float64(doc)/float64(len(d.boundaries)))) 323 324 if opts.DebugScore { 325 // To make the debug output easier to read, we split the score into the query 326 // dependent score and the tiebreaker 327 score := math.Trunc(fileMatch.Score / ScoreOffset) 328 tiebreaker := fileMatch.Score - score*ScoreOffset 329 fileMatch.Debug = fmt.Sprintf("score: %d (%.2f) <- %s", int(score), tiebreaker, strings.TrimSuffix(fileMatch.Debug, ", ")) 330 } 331} 332 333// scoreFilesUsingBM25 computes the score according to BM25, the most common scoring algorithm for text search: 334// https://en.wikipedia.org/wiki/Okapi_BM25. Note that we treat the inverse document frequency (idf) as constant. This 335// is supported by our evaluations which showed that for keyword style queries, idf can down-weight the score of some 336// keywords too much, leading to a worse ranking. The intuition is that each keyword is important independently of how 337// frequent it appears in the corpus. 338// 339// Unlike standard file scoring, this scoring strategy ignores all other signals including document ranks. This keeps 340// things simple for now, since BM25 is not normalized and can be tricky to combine with other scoring signals. It also 341// ignores the individual LineMatch and ChunkMatch scores, instead calculating a score over all matches in the file. 342func (d *indexData) scoreFilesUsingBM25(fileMatch *zoekt.FileMatch, doc uint32, tf map[string]int, opts *zoekt.SearchOptions) { 343 // Use standard parameter defaults used in Lucene (https://lucene.apache.org/core/10_1_0/core/org/apache/lucene/search/similarities/BM25Similarity.html) 344 k, b := 1.2, 0.75 345 346 averageFileLength := float64(d.boundaries[d.numDocs()]) / float64(d.numDocs()) 347 // This is very unlikely, but explicitly guard against division by zero. 348 if averageFileLength == 0 { 349 averageFileLength++ 350 } 351 352 // Compute the file length ratio. Usually the calculation would be based on terms, but using 353 // bytes should work fine, as we're just computing a ratio. 354 fileLength := float64(d.boundaries[doc+1] - d.boundaries[doc]) 355 356 L := fileLength / averageFileLength 357 358 score := 0.0 359 sumTF := 0 // Just for debugging 360 for _, f := range tf { 361 sumTF += f 362 score += tfScore(k, b, L, f) 363 } 364 365 fileMatch.Score = score 366 367 if opts.DebugScore { 368 fileMatch.Debug = fmt.Sprintf("bm25-score: %.2f <- sum-termFrequencies: %d, length-ratio: %.2f", score, sumTF, L) 369 } 370}