Skip to content

Incorrect `preview` returned in search API when using patternType: structural

Created by: felixfbecker

Check out this search query: https://sourcegraph.com/search?q=repo:%5Egithub%5C.com/sourcegraph/sourcegraph%24+prometheus.MustRegister%28:%5Bcollector%5D%29&patternType=structural

It includes for example this result:

image

If we do the same search in the API Console, we get this result:

"lineMatches": [
  {
    "preview": "prometheus.MustRegister(requestDuration)",
    "offsetAndLengths": [[1, 40]]
  }
]

My understanding (the docs are very fuzzy on this) is that preview is supposed to be the whole line of the match, while offsetAndLengths is 0-based offsets from the beginning of the line with the ranges to be highlighted. This is supported by this line of code:

https://github.com/sourcegraph/sourcegraph/blob/2a1cd8a30c72780ad884159161d0ec828cfe69a3/cmd/frontend/graphqlbackend/zoekt.go#L241

It is also how it works when using patternType: literal (API Console):

"lineMatches": [
   {
     "preview": "\tprometheus.MustRegister(requestDuration)",
     "offsetAndLengths": [[1, 24]]
   }
]

Notice how in both cases the offsetAndLengths starts at character 1 (i.e. the 2nd character, or the first character after the tab), but with patternType: structural, the preview does not contain the leading tab character (i.e. not the whole line), meaning that if the CLI wants to display preview and highlight the matching ranges it will fail with index out of bounds errors.