diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ad9b410..ae35b04 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "sourcegraph", "description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.", - "version": "0.8.1", + "version": "0.8.2", "author": { "name": "context4ai" }, diff --git a/cli/README.md b/cli/README.md index cd6095e..1640c43 100644 --- a/cli/README.md +++ b/cli/README.md @@ -38,7 +38,7 @@ A token acts as its owner: it reads what you can read, manages repositories you | MCP | `mcp` prints a client configuration | | Connection | `doctor` checks DNS, each IPv4/IPv6 address, HTTPS and the sign-in, and says what to do | -`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours). +`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--contains TEXT] [--limit N] [--access]` shows service logs of all instances (default: warnings and errors, last 24 hours); `--access` reads the request log instead (one line per request with route, method, status and duration), and `--contains` keeps lines containing a text such as a request id. `sourcegraph read ` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`. diff --git a/cli/package.json b/cli/package.json index 34854e8..1633e5e 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@c4a/sourcegraph", - "version": "0.8.1", + "version": "0.8.2", "description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.", "license": "MIT", "type": "module", diff --git a/cli/src/main.ts b/cli/src/main.ts index d997f72..1a57b48 100644 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -69,6 +69,13 @@ function unindexedNote(r: any) { if (m.MissingObjects > 0) console.error(`note: ${m.MissingObjects} file(s) could not be read (objects missing locally) and were not searched`); if (m.UncoveredGroups?.length) console.error(`note: not searched (contents not local at this commit): ${m.UncoveredGroups.join(', ')}`); } +// partialNote tells a human reader why an indexed search is incomplete and +// what to do, so a short or empty answer is not read as "not in the code". +function partialNote(r: any) { + const m = r?.Meta; + if (!m?.Partial || m.Unindexed || jsonOutput) return; + console.error(`note: partial result${m.PartialReasons?.length ? ' (' + m.PartialReasons.join(', ') + ')' : ''}${m.Hint ? ': ' + m.Hint : ''}`); +} // hybridNote tells a human reader that a commit without its own index was // answered exactly from a nearby index plus the files changed since. function hybridNote(r: any) { @@ -372,6 +379,7 @@ const C: Record = { servedNote(r); unindexedNote(r); hybridNote(r); + partialNote(r); if (jsonOutput) return r; const files = r.Result?.Files || []; if (o.l) return files.map((f: any) => f.FileName).join('\n') || '(no matches)'; @@ -482,7 +490,10 @@ const C: Record = { admin credentials [get] | admin credentials set [--token T|--stdin] | admin credentials clear admin query-errors [ID] [--repo R] [--limit N] [--after CURSOR] | admin clear-jobs [--success] [--failed] admin cluster | admin instances | admin statistics [--window MIN] - admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N] service logs of all instances (default: warnings and errors, last 24 hours)`, summary: 'Site administration (administrators)', options: { query: { type: 'string' }, token: { type: 'string' }, stdin: { type: 'boolean' }, after: { type: 'string' }, success: { type: 'boolean' }, failed: { type: 'boolean' }, window: { type: 'string' }, repo: { type: 'string' }, limit: { type: 'string' }, hours: { type: 'string' }, level: { type: 'string' }, msg: { type: 'string' } }, run: async (ctx, a, o) => { + admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--contains TEXT] [--limit N] [--access] + service logs of all instances (default: warnings and errors, last 24 hours); + --access: the request log (one line per request: route, method, status, duration); + --contains: lines containing TEXT, e.g. a request id`, summary: 'Site administration (administrators)', options: { query: { type: 'string' }, token: { type: 'string' }, stdin: { type: 'boolean' }, after: { type: 'string' }, success: { type: 'boolean' }, failed: { type: 'boolean' }, window: { type: 'string' }, repo: { type: 'string' }, limit: { type: 'string' }, hours: { type: 'string' }, level: { type: 'string' }, msg: { type: 'string' }, contains: { type: 'string' }, access: { type: 'boolean' } }, run: async (ctx, a, o) => { const [sub, ...rest] = a; switch (sub) { case 'settings': return siteSettings(ctx, rest); @@ -501,9 +512,9 @@ const C: Record = { case 'instances': return ctx.client.call('/api/admin/v1/instances'); case 'statistics': return ctx.client.call('/api/admin/v1/statistics', { query: { window: o.window } }); case 'logs': { - const r = await ctx.client.call('/api/admin/v1/logs', { query: { hours: o.hours, level: o.level, msg: o.msg, limit: o.limit } }); + const r = await ctx.client.call('/api/admin/v1/logs', { query: { hours: o.hours, level: o.level, msg: o.msg, limit: o.limit, contains: o.contains, category: o.access ? 'access' : undefined } }); if (jsonOutput) return r; - const head = `${r.from} .. ${r.to} · ${r.level} and above · ${r.scanned_lines} lines scanned`; + const head = `${r.category === 'access' ? 'request log · ' : ''}${r.from} .. ${r.to} · ${r.level} and above · ${r.scanned_lines} lines scanned`; const sum = table((r.summary || []).map((x: any) => ({ count: x.count, level: x.level, msg: x.msg, code: x.code || '', last: x.last })), ['count', 'level', 'msg', 'code', 'last']); const lines = (r.lines || []).map((l: any) => { const { time, level, msg, instance, ...rest } = l; return `${time} ${level} ${instance} ${msg} ${JSON.stringify(rest)}`; }).join('\n'); return [head, '', sum, '', lines, r.truncated ? '\n(newest lines only; raise --limit or narrow with --msg)' : ''].join('\n'); diff --git a/cli/src/search-partial.test.ts b/cli/src/search-partial.test.ts new file mode 100644 index 0000000..1b486d6 --- /dev/null +++ b/cli/src/search-partial.test.ts @@ -0,0 +1,42 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// A search API answering one partial result with its reason and hint. +async function partialServer(meta: Record) { + const server = createServer((_req, res) => { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ Meta: { Status: 'partial', Partial: true, Commit: 'a'.repeat(40), ...meta }, Result: { Files: [], FileCount: 0 } })); + }); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + return { url: `http://127.0.0.1:${(server.address() as any).port}`, close: () => server.close() }; +} + +function cli(url: string, ...args: string[]) { + const env = { ...process.env, XDG_CONFIG_HOME: mkdtempSync(join(tmpdir(), 'sg-cli-')) } as Record; + delete env.SOURCEGRAPH_API_TOKEN; + delete env.SOURCEGRAPH_URL; + return new Promise<{ status: number | null; stdout: string; stderr: string }>(resolve => { + const child = spawn(process.execPath, [fileURLToPath(new URL('main.ts', import.meta.url)), '--url', url, ...args], { env }); + let stdout = '', stderr = ''; + child.stdout.on('data', (d: Buffer) => { stdout += d; }); + child.stderr.on('data', (d: Buffer) => { stderr += d; }); + child.on('close', (status: number | null) => resolve({ status, stdout, stderr })); + }); +} + +test('search says why a result is partial and what to do', async () => { + const s = await partialServer({ PartialReasons: ['deadline'], Hint: 'The search reached its time limit with 9465 candidate files unchecked.' }); + try { + const r = await cli(s.url, 'search', '-r', 'org/repo', '-i', 'location.?auth'); + assert.equal(r.status, 0); + assert.match(r.stderr, /note: partial result \(deadline\): The search reached its time limit with 9465 candidate files unchecked\./); + const json = await cli(s.url, 'search', '-r', 'org/repo', '--json', 'x'); + assert.doesNotMatch(json.stderr, /partial result/); + } finally { s.close(); } +}); diff --git a/cli/src/version.ts b/cli/src/version.ts index 223bb57..96f2eef 100644 --- a/cli/src/version.ts +++ b/cli/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.8.1'; +export const VERSION = '0.8.2'; diff --git a/docs/interfaces.md b/docs/interfaces.md index 999c57a..2209ec9 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -72,18 +72,19 @@ Repository routes take `?repo=owner/repository`. | `GET /sourcegraph/healthz`, `GET /sourcegraph/readyz` | Liveness and readiness | | `GET /sourcegraph/v1/capabilities` | Supported operations | | `GET /sourcegraph/v1/repos` | Repository catalog; signed-in callers also get each repository's `managers` | +| `GET /sourcegraph/v1/repo/catalog`, `GET /sourcegraph/v1/tag/list` | The repository catalog (`{items, next_after}`, 100 per page, `after` for the next page) and the tag counts (`{items}`) as objects, for clients that cannot take a top-level array | | `GET /sourcegraph/v1/code-sources` | Configured code sources in display order: `id/name/host/username/anonymous/editable/locked` | | `GET /sourcegraph/v1/repo/availability` | Indexed commits and readiness; `/v1/repo/commits` is an alias | | `GET /sourcegraph/v1/repo/plugins` | Read plugins available for a revision | | `POST /sourcegraph/v1/repo/resolve` | Resolve a branch, tag or SHA to a fixed commit; see [Branches, tags and resolve](#branches-tags-and-resolve) | | `GET /sourcegraph/v1/repo/refs` | List and search branches and tags (`kind/query/author/title/since/until/sort/first/after`) | -| `POST /sourcegraph/v1/repo/read` | Read a line range | +| `POST /sourcegraph/v1/repo/read` | Read a line range; optional `PluginMode`/`Plugins` run read plugins (see [read plugins](ref/repository-plugins.md)) | | `POST /sourcegraph/v1/repo/list` | List a directory | -| `POST /sourcegraph/v1/repo/diff` | Changed paths between two commits; `NamesOnly` returns metadata only (see [remote reads](#remote-reads)) | +| `POST /sourcegraph/v1/repo/diff` | Changed paths between two commits with patches (64 KiB per file, 256 KiB per page; one page runs two Git processes); `NamesOnly` returns metadata only (see [remote reads](#remote-reads)) | | `POST /sourcegraph/v1/repo/blob`, `POST /sourcegraph/v1/repo/blobs` | Raw file bytes, one or a batch (see [remote reads](#remote-reads)) | | `POST /sourcegraph/v1/repo/scope-availability` | Whether a commit and paths can be read here | | `POST /sourcegraph/v1/repo/directories` | Every directory below a path, recursively | -| `POST /sourcegraph/api/search` | Search, with the same options as the CLI | +| `POST /sourcegraph/api/search` | Search, with the same options as the CLI. A partial answer carries `Meta.PartialReasons` (`deadline`, `match_limit`, `engine_error`, `filter_candidates`, `files_skipped`, `scan_stopped`) and `Meta.Hint` | | `POST /sourcegraph/api/admin/v1/repo/prepare` | Queue indexing or synchronization | Repository registration, maintenance, statistics and site settings live under `/sourcegraph/api/admin/` and are used by the website's administration pages. Use the Connect page for current request examples. diff --git a/internal/gitstore/diff.go b/internal/gitstore/diff.go index b896c1c..df5d2b8 100644 --- a/internal/gitstore/diff.go +++ b/internal/gitstore/diff.go @@ -7,7 +7,6 @@ import ( "encoding/json" "sort" "strings" - "unicode/utf8" "github.com/context4ai/sourcegraph/internal/contract" ) @@ -154,41 +153,39 @@ func (s *Store) PatchChanges(ctx context.Context, repo, base, head string, selec if err != nil { return nil, remaining, err } + // One numstat and one patch process serve the whole page: on network + // storage each git diff re-reads both root trees, and per-file processes + // made a 100-file page take tens of seconds. + paths := make([]string, 0, len(selected)) + for _, c := range selected { + paths = append(paths, c.Path) + } + binary, err := s.binaryPaths(ctx, p, base, head, paths) + if err != nil { + return nil, remaining, err + } + text := []string{} + for _, path := range paths { + if !binary[path] { + text = append(text, path) + } + } + patches, err := s.pagePatches(ctx, p, base, head, text, remaining) + if err != nil { + return nil, remaining, err + } out := make([]Change, 0, len(selected)) for _, c := range selected { c.Patch = "" - c.Binary = false + c.Binary = binary[c.Path] c.PatchTruncated = false c.OldMode, c.NewMode = "", "" // patch diffs keep their original fields - // Neither operation can execute repository-provided diff drivers or fetch. - stat, e := s.run(ctx, p, 16384, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--numstat", "-z", base, head, "--", c.Path) - if e != nil { - return nil, remaining, e - } - c.Binary = bytes.HasPrefix(stat, []byte("-\t-\t")) if !c.Binary && remaining > 0 { - limit := 64 << 10 - if remaining < limit { - limit = remaining - } - patch, truncated, e := s.runPrefix(ctx, p, limit, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-color", "--submodule=short", "--unified=3", base, head, "--", c.Path) - if e != nil { - return nil, remaining, e - } - if truncated { - // A patch over its share returns its first whole lines; only - // what is returned is taken from the page budget. - c.PatchTruncated = true - if i := bytes.LastIndexByte(patch, '\n'); i >= 0 { - patch = patch[:i+1] - } else { - patch = nil - } - } - if !utf8.Valid(patch) { - c.Binary, c.PatchTruncated = true, false + patch, truncated, ok := cutPatch(patches[c.Path], remaining) + if !ok { + c.Binary = true } else { - c.Patch = string(patch) + c.Patch, c.PatchTruncated = string(patch), truncated remaining -= len(patch) } } else if !c.Binary { diff --git a/internal/gitstore/diff_page.go b/internal/gitstore/diff_page.go new file mode 100644 index 0000000..09c0dcd --- /dev/null +++ b/internal/gitstore/diff_page.go @@ -0,0 +1,278 @@ +package gitstore + +import ( + "bufio" + "bytes" + "context" + "io" + "math" + "strconv" + "strings" + "sync/atomic" + "unicode/utf8" + + "github.com/context4ai/sourcegraph/internal/contract" +) + +// maxFilePatchBytes is one file's patch share of a page. +const maxFilePatchBytes = 64 << 10 + +// pagePatchStreamBytes bounds one page's patch stream. Files whose sections +// were not complete when it is reached are read one at a time, as before. +var pagePatchStreamBytes = 32 << 20 + +// pageFallbacks counts pages that read some patches one file at a time; +// pageBudgetStops pages whose stream stopped once the budget was spent. +var pageFallbacks, pageBudgetStops atomic.Int64 + +var patchArgs = []string{"diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-color", "--submodule=short", "--unified=3"} + +// filePatch is the start of one file's patch (at most maxFilePatchBytes) and +// the patch's full size. +type filePatch struct { + data []byte + size int +} + +// binaryPaths reports the paths git counts as binary, from one numstat run. +func (s *Store) binaryPaths(ctx context.Context, p, base, head string, paths []string) (map[string]bool, error) { + args := append([]string{"diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--numstat", "-z", base, head, "--"}, paths...) + raw, err := s.run(ctx, p, 1<<20, args...) + if err != nil { + return nil, err + } + out := map[string]bool{} + seen := map[string]bool{} + for _, record := range bytes.Split(raw, []byte{0}) { + fields := bytes.SplitN(record, []byte{'\t'}, 3) + if len(fields) != 3 { + continue + } + path := string(fields[2]) + // A type change has two records; the first decides, as a per-path run did. + if !seen[path] { + seen[path] = true + out[path] = bytes.Equal(fields[0], []byte("-")) && bytes.Equal(fields[1], []byte("-")) + } + } + return out, nil +} + +// cutPatch is the part of a file's patch a page returns with remaining bytes +// of budget: its share (at most maxFilePatchBytes), cut after the last whole +// line when the patch is larger. ok is false for a patch that is not UTF-8. +func cutPatch(got filePatch, remaining int) (patch []byte, truncated, ok bool) { + limit := min(maxFilePatchBytes, remaining) + patch = got.data + if got.size > limit { + // A patch over its share returns its first whole lines; only what is + // returned is taken from the page budget. + truncated = true + patch = patch[:min(limit, len(patch))] + if i := bytes.LastIndexByte(patch, '\n'); i >= 0 { + patch = patch[:i+1] + } else { + patch = nil + } + } + if !utf8.Valid(patch) { + return nil, false, false + } + return patch, truncated, true +} + +// pagePatches runs one git diff for the page and splits it at file headers. +// A path's sections (a type change has two) are concatenated in order. paths +// are in page order; once the files before the first incomplete one have +// spent the budget, later files get no patch and the stream stops. +func (s *Store) pagePatches(ctx context.Context, p, base, head string, paths []string, budget int) (map[string]filePatch, error) { + out := map[string]filePatch{} + if len(paths) == 0 { + return out, nil + } + wanted := map[string]bool{} + for _, path := range paths { + wanted[path] = true + } + if budget <= 0 || allSpent(budget, paths) { + skipRest(out, map[string]bool{}, paths) + return out, nil + } + ctx, cancel := context.WithTimeout(ctx, s.commandTimeout(ctx)) + defer cancel() + args := append(append(append([]string{}, patchArgs...), base, head, "--"), paths...) + c := s.command(ctx, p, args...) + stdout, err := c.StdoutPipe() + if err != nil { + return nil, contract.Fail("GIT_OPERATION_FAILED", "Git could not complete the operation.", 500) + } + c.Stderr = io.Discard + if err = c.Start(); err != nil { + return nil, contract.Fail("GIT_OPERATION_FAILED", "Git could not complete the operation.", 500) + } + complete := map[string]bool{} + current, streamed, overflow, unparsed, spent := "", 0, false, false, false + // budgetSpent walks the page in order while files are complete; the budget + // left after them decides whether later patches are still needed. + walked, left := 0, budget + budgetSpent := func() bool { + for walked < len(paths) && left > 0 && complete[paths[walked]] { + if patch, _, ok := cutPatch(out[paths[walked]], left); ok { + left -= len(patch) + } + walked++ + } + if left <= 0 { + return true + } + // A share shorter than a file's header line returns nothing of it. + return allSpent(left, paths[walked:]) + } + add := func(b []byte) { + got := out[current] + if room := maxFilePatchBytes + 1 - len(got.data); room > 0 { + got.data = append(got.data, b[:min(room, len(b))]...) + } + got.size += len(b) + out[current] = got + } + r := bufio.NewReaderSize(stdout, 64<<10) + atLineStart := true + for { + line, e := r.ReadSlice('\n') + if len(line) > 0 { + streamed += len(line) + if streamed > pagePatchStreamBytes { + overflow = true + break + } + if atLineStart && bytes.HasPrefix(line, []byte("diff --git ")) { + path, ok := headerPath(strings.TrimSuffix(string(line[len("diff --git "):]), "\n")) + if !ok || !wanted[path] { + unparsed = true + break + } + if current != "" && current != path { + complete[current] = true + if budgetSpent() { + spent = true + break + } + } + current = path + } + if current != "" { + add(line) + } + atLineStart = line[len(line)-1] == '\n' + } + if e == bufio.ErrBufferFull { + continue + } + if e != nil { + if current != "" { + complete[current] = true + } + break + } + } + if overflow || unparsed || spent { + _ = c.Process.Kill() + } else { + _, _ = io.Copy(io.Discard, stdout) + } + waitErr := c.Wait() + if ctx.Err() != nil { + return nil, ctx.Err() + } + if spent { + pageBudgetStops.Add(1) + skipRest(out, complete, paths) + return out, nil + } + if !overflow && !unparsed { + if waitErr != nil { + return nil, contract.Fail("GIT_OPERATION_FAILED", "Git could not complete the operation.", 500) + } + return out, nil + } + // Read the files whose sections did not finish one at a time. + pageFallbacks.Add(1) + budgetSpent() + for i, path := range paths { + if complete[path] { + continue + } + if i >= walked && spentBefore(left, path) { + skipRest(out, complete, paths[i:i+1]) + continue // the budget left before this file returns none of it + } + data, truncated, e := s.runPrefix(ctx, p, maxFilePatchBytes+1, append(append(append([]string{}, patchArgs...), base, head, "--"), path)...) + if e != nil { + return nil, e + } + size := len(data) + if truncated { + size++ // only "larger than the share" matters + } + out[path] = filePatch{data: data, size: size} + } + return out, nil +} + +// skipRest records the incomplete paths as patches larger than any share: +// every changed path has a section, and none of it is returned. +func skipRest(out map[string]filePatch, complete map[string]bool, paths []string) { + for _, path := range paths { + if !complete[path] { + out[path] = filePatch{size: math.MaxInt} + } + } +} + +// allSpent reports whether a budget returns nothing of any of the paths. +func allSpent(budget int, paths []string) bool { + for _, path := range paths { + if !spentBefore(budget, path) { + return false + } + } + return true +} + +// spentBefore reports whether a share of left bytes returns nothing of path's +// patch: less than its first line, the header (longer still when quoted). +func spentBefore(left int, path string) bool { + return left < len("diff --git a/ b/\n")+2*len(path) +} + +// headerPath reads the path of "a/ b/" (no renames: both sides +// name the same path), C-quoted when core.quotePath applies. +func headerPath(rest string) (string, bool) { + if strings.HasPrefix(rest, `"`) { + end := 1 + for end < len(rest) && rest[end] != '"' { + if rest[end] == '\\' { + end++ + } + end++ + } + if end >= len(rest) { + return "", false + } + a, err := strconv.Unquote(rest[:end+1]) + if err != nil || !strings.HasPrefix(a, "a/") { + return "", false + } + return a[2:], true + } + if len(rest) < 5 || (len(rest)-5)%2 != 0 { + return "", false + } + n := (len(rest) - 5) / 2 + a, b := rest[:2+n], rest[2+n:] + if !strings.HasPrefix(a, "a/") || b != " b/"+a[2:] { + return "", false + } + return a[2:], true +} diff --git a/internal/gitstore/diff_page_test.go b/internal/gitstore/diff_page_test.go new file mode 100644 index 0000000..0363d9d --- /dev/null +++ b/internal/gitstore/diff_page_test.go @@ -0,0 +1,243 @@ +package gitstore + +import ( + "bytes" + "context" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "unicode/utf8" +) + +func diffGit(t *testing.T, dir string, args ...string) string { + t.Helper() + c := exec.Command("git", args...) + c.Dir = dir + c.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1", "GIT_AUTHOR_NAME=F", "GIT_AUTHOR_EMAIL=f@example.test", "GIT_COMMITTER_NAME=F", "GIT_COMMITTER_EMAIL=f@example.test") + out, err := c.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v %s", args, err, out) + } + return strings.TrimSpace(string(out)) +} + +// diffFixture commits base and head trees and serves them from a bare store. +func diffFixture(t *testing.T, base, head map[string]string, links map[string]string) (*Store, string, string) { + t.Helper() + work := t.TempDir() + diffGit(t, work, "init", "-q") + write := func(files map[string]string, links map[string]string) string { + diffGit(t, work, "rm", "-rq", "--ignore-unmatch", ".") + for name, content := range files { + // A "|x" suffix marks an executable file. + mode := os.FileMode(0o644) + if n, ok := strings.CutSuffix(name, "|x"); ok { + name, mode = n, 0o755 + } + p := filepath.Join(work, name) + _ = os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(content), mode); err != nil { + t.Fatal(err) + } + _ = os.Chmod(p, mode) + } + for name, target := range links { + _ = os.MkdirAll(filepath.Dir(filepath.Join(work, name)), 0o755) + if err := os.Symlink(target, filepath.Join(work, name)); err != nil { + t.Fatal(err) + } + } + diffGit(t, work, "add", "-A") + diffGit(t, work, "commit", "-q", "--allow-empty", "-m", "c") + return diffGit(t, work, "rev-parse", "HEAD") + } + b := write(base, nil) + h := write(head, links) + root := t.TempDir() + dir, err := RepositoryDir(root, "org/repo") + if err != nil { + t.Fatal(err) + } + _ = os.MkdirAll(filepath.Dir(dir), 0o755) + diffGit(t, root, "clone", "-q", "--bare", work, dir) + g, err := New(root) + if err != nil { + t.Fatal(err) + } + return g, b, h +} + +// perFilePatches is the previous implementation: two git processes per file. +func perFilePatches(t *testing.T, s *Store, base, head string, selected []Change, remaining int) []Change { + ctx := context.Background() + p, _ := s.repoPath("org/repo") + out := []Change{} + for _, c := range selected { + c.Patch, c.Binary, c.PatchTruncated, c.OldMode, c.NewMode = "", false, false, "", "" + stat, e := s.run(ctx, p, 16384, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--numstat", "-z", base, head, "--", c.Path) + if e != nil { + t.Fatal(e) + } + c.Binary = bytes.HasPrefix(stat, []byte("-\t-\t")) + if !c.Binary && remaining > 0 { + limit := min(64<<10, remaining) + patch, truncated, e := s.runPrefix(ctx, p, limit, append(append([]string{}, patchArgs...), base, head, "--", c.Path)...) + if e != nil { + t.Fatal(e) + } + if truncated { + c.PatchTruncated = true + if i := bytes.LastIndexByte(patch, '\n'); i >= 0 { + patch = patch[:i+1] + } else { + patch = nil + } + } + if !utf8.Valid(patch) { + c.Binary, c.PatchTruncated = true, false + } else { + c.Patch = string(patch) + remaining -= len(patch) + } + } else if !c.Binary { + c.PatchTruncated = true + } + out = append(out, c) + } + return out +} + +func pageFixture(t *testing.T) (*Store, string, string) { + big := strings.Repeat("line of a large generated file\n", 4000) // > 64 KiB + base := map[string]string{ + "a.txt": "one\ntwo\n", "b/deleted.txt": "gone\n", "bin.dat": "a\x00b", "mode.sh": "echo\n", + "space name.txt": "x\n", "quote\"d.txt": "q\n", "ünï.txt": "u\n", + "big.txt": "start\n", "typed": "was a file\n", "a-b.txt": "1\n", "a/x.txt": "2\n", "a.c": "3\n", + "same.txt": "unchanged\n", "latin1.txt": "ok\n", + } + head := map[string]string{ + "a.txt": "one\nthree\n", "bin.dat": "a\x00c", "mode.sh|x": "echo\n", "new/added.txt": "hello\n", + "space name.txt": "y\n", "quote\"d.txt": "r\n", "ünï.txt": "v\n", + "big.txt": big, "a-b.txt": "10\n", "a/x.txt": "20\n", "a.c": "30\n", "same.txt": "unchanged\n", + "latin1.txt": "caf\xe9\n", + } + g, b, h := diffFixture(t, base, head, map[string]string{"typed": "a.txt"}) + return g, b, h +} + +func TestPagePatchesMatchPerFileProcesses(t *testing.T) { + g, base, head := pageFixture(t) + ctx := context.Background() + changes, err := g.Changes(ctx, "org/repo", base, head) + if err != nil || len(changes) < 12 { + t.Fatalf("changes %d %v", len(changes), err) + } + fallbacks := pageFallbacks.Load() + full, _, _ := g.PatchChanges(ctx, "org/repo", base, head, changes, MaxPatchBytes) + if pageFallbacks.Load() != fallbacks { + t.Fatal("an ordinary page fell back to per-file processes") + } + byPath := map[string]Change{} + for _, c := range full { + byPath[c.Path] = c + } + for path, check := range map[string]func(Change) bool{ + "big.txt": func(c Change) bool { return c.PatchTruncated && strings.HasSuffix(c.Patch, "\n") }, + "bin.dat": func(c Change) bool { return c.Binary && c.Patch == "" }, + "quote\"d.txt": func(c Change) bool { return strings.Contains(c.Patch, "+r") }, + "ünï.txt": func(c Change) bool { return strings.Contains(c.Patch, "+v") }, + "space name.txt": func(c Change) bool { return strings.Contains(c.Patch, "+y") }, + "typed": func(c Change) bool { return strings.Count(c.Patch, "diff --git") == 2 }, + "mode.sh": func(c Change) bool { return strings.Contains(c.Patch, "new mode 100755") }, + "b/deleted.txt": func(c Change) bool { return strings.Contains(c.Patch, "deleted file") }, + "latin1.txt": func(c Change) bool { return c.Binary && c.Patch == "" }, + } { + if c, ok := byPath[path]; !ok || !check(c) { + t.Fatalf("%q: %+v", path, c) + } + } + for _, budget := range []int{MaxPatchBytes, 70 << 10, 26 << 10, 10, 0} { + got, rest, err := g.PatchChanges(ctx, "org/repo", base, head, changes, budget) + if err != nil { + t.Fatal(err) + } + want := perFilePatches(t, g, base, head, changes, budget) + if !reflect.DeepEqual(got, want) { + for i := range got { + if !reflect.DeepEqual(got[i], want[i]) { + t.Fatalf("budget %d %q:\n got %+v\nwant %+v", budget, got[i].Path, got[i], want[i]) + } + } + t.Fatalf("budget %d differs", budget) + } + used := 0 + for _, c := range got { + used += len(c.Patch) + } + if rest != budget-used { + t.Fatalf("budget %d remaining %d used %d", budget, rest, used) + } + } +} + +func TestPagePatchesFallBackWhenTheStreamIsTooLarge(t *testing.T) { + g, base, head := pageFixture(t) + ctx := context.Background() + changes, _ := g.Changes(ctx, "org/repo", base, head) + want := perFilePatches(t, g, base, head, changes, MaxPatchBytes) + saved := pagePatchStreamBytes + defer func() { pagePatchStreamBytes = saved }() + for _, limit := range []int{1, 300, 40 << 10} { + pagePatchStreamBytes = limit + before := pageFallbacks.Load() + got, _, err := g.PatchChanges(ctx, "org/repo", base, head, changes, MaxPatchBytes) + if err != nil || !reflect.DeepEqual(got, want) || pageFallbacks.Load() == before { + t.Fatalf("stream limit %d: %v", limit, err) + } + } +} + +func TestHeaderPath(t *testing.T) { + for rest, want := range map[string]string{ + "a/x b/x": "x", + "a/a b/c b/a b/c": "a b/c", + `"a/quote\"d" "b/quote\"d"`: `quote"d`, + `"a/\303\274.txt" "b/\303\274.txt"`: "ü.txt", + `"a/tab\tx" "b/tab\tx"`: "tab\tx", + } { + if got, ok := headerPath(rest); !ok || got != want { + t.Fatalf("%s: %q %v", rest, got, ok) + } + } + for _, rest := range []string{"a/x b/y", "x", `"a/unterminated`, "a/xx b/x"} { + if _, ok := headerPath(rest); ok { + t.Fatalf("accepted %s", rest) + } + } +} + +func TestPagePatchesStopOnceTheBudgetIsSpent(t *testing.T) { + base, head := map[string]string{}, map[string]string{} + for i := 0; i < 30; i++ { + name := "gen/" + string(rune('a'+i%26)) + strings.Repeat("x", i/26) + ".txt" + base[name] = "old\n" + head[name] = strings.Repeat("generated line\n", 8000) + } + g, b, h := diffFixture(t, base, head, nil) + ctx := context.Background() + changes, err := g.Changes(ctx, "org/repo", b, h) + if err != nil || len(changes) != 30 { + t.Fatalf("changes %d %v", len(changes), err) + } + stops, fallbacks := pageBudgetStops.Load(), pageFallbacks.Load() + got, rest, err := g.PatchChanges(ctx, "org/repo", b, h, changes, MaxPatchBytes) + if err != nil || rest >= 64<<10 || pageBudgetStops.Load() != stops+1 || pageFallbacks.Load() != fallbacks { + t.Fatalf("stop not taken: rest=%d err=%v", rest, err) + } + if want := perFilePatches(t, g, b, h, changes, MaxPatchBytes); !reflect.DeepEqual(got, want) { + t.Fatal("early stop changed the page") + } +} diff --git a/internal/httpserver/catalog_test.go b/internal/httpserver/catalog_test.go new file mode 100644 index 0000000..4478641 --- /dev/null +++ b/internal/httpserver/catalog_test.go @@ -0,0 +1,61 @@ +package httpserver + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/context4ai/sourcegraph/internal/config" + "github.com/context4ai/sourcegraph/internal/sitesettings" +) + +func TestCatalogAndTagListMatchTheArrayEndpoints(t *testing.T) { + admin, alice := hexID("admin"), hexID("alice") + s := newSiteWith(t, config.Defaults(), map[string]string{"admin": admin, "alice": alice}, admin) + rev := s.settings.Snapshot().Access.Revision + if _, err := s.settings.Update(context.Background(), sitesettings.AccessName, rev, []byte(`{"public_read":false,"allow_registration":true,"allow_user_repositories":true}`), "sso:admin"); err != nil { + t.Fatal(err) + } + body := `{"name":"context4ai/private","policy":{"branches":["main"],"count":10},"code_provider":"github","public_read":false,"tags":["team-a"]}` + if code, out := s.call(alice, "POST", "/sourcegraph/api/admin/v1/repos", body, "Idempotency-Key", "register-private"); code != 202 { + t.Fatalf("register: %d %v", code, out) + } + get := func(path string) (int, []byte) { + r := httptest.NewRequest("GET", path, nil) + r.AddCookie(&http.Cookie{Name: "sourcegraph_session", Value: "cookie-" + alice}) + w := httptest.NewRecorder() + s.handler.ServeHTTP(w, r) + return w.Code, w.Body.Bytes() + } + _, rows := get("/sourcegraph/v1/repos") + code, raw := get("/sourcegraph/v1/repo/catalog") + var page struct { + Items json.RawMessage `json:"items"` + NextAfter *string `json:"next_after"` + } + var want []any + _ = json.Unmarshal(rows, &want) + wantJSON, _ := json.Marshal(want) + var items []any + if code != 200 || json.Unmarshal(raw, &page) != nil || json.Unmarshal(page.Items, &items) != nil || len(items) != 1 || page.NextAfter == nil || *page.NextAfter != "" { + t.Fatalf("catalog: %d %s", code, raw) + } + if got, _ := json.Marshal(items); string(got) != string(wantJSON) { + t.Fatalf("catalog %s, repos %s", got, wantJSON) + } + code, raw = get("/sourcegraph/v1/tag/list") + var tags struct { + Items []map[string]any `json:"items"` + } + if code != 200 || json.Unmarshal(raw, &tags) != nil || len(tags.Items) != 1 || tags.Items[0]["tag"] != "team-a" { + t.Fatalf("tags: %d %s", code, raw) + } + // An anonymous caller on a site without public reading signs in first. + w := httptest.NewRecorder() + s.handler.ServeHTTP(w, httptest.NewRequest("GET", "/sourcegraph/v1/tag/list", nil)) + if w.Code != 401 { + t.Fatalf("anonymous tag list: %d", w.Code) + } +} diff --git a/internal/httpserver/query_auth.go b/internal/httpserver/query_auth.go index d5fe069..209febc 100644 --- a/internal/httpserver/query_auth.go +++ b/internal/httpserver/query_auth.go @@ -15,7 +15,7 @@ import ( func retrievalRoute(r *http.Request) bool { if r.Method == "GET" { switch r.URL.Path { - case Prefix + "/v1/repo/plugins", Prefix + "/v1/capabilities", Prefix + "/v1/code-sources", Prefix + "/v1/repos", Prefix + "/v1/tags", Prefix + "/v1/repo/availability", Prefix + "/v1/repo/refs", Prefix + "/v1/repo/commits": + case Prefix + "/v1/repo/plugins", Prefix + "/v1/capabilities", Prefix + "/v1/code-sources", Prefix + "/v1/repos", Prefix + "/v1/tags", Prefix + "/v1/repo/catalog", Prefix + "/v1/tag/list", Prefix + "/v1/repo/availability", Prefix + "/v1/repo/refs", Prefix + "/v1/repo/commits": return true } } diff --git a/internal/httpserver/repository_access.go b/internal/httpserver/repository_access.go index f157b72..e790b24 100644 --- a/internal/httpserver/repository_access.go +++ b/internal/httpserver/repository_access.go @@ -209,6 +209,28 @@ type catalogRow struct { CanManage bool `json:"can_manage"` } +// catalogPageSize is the number of repositories in one catalog page. +const catalogPageSize = 100 + +// repoCatalog is one page of GET /v1/repo/catalog: Items as in GET /v1/repos, +// and NextAfter, the cursor of the next page ("" on the last page). +type repoCatalog struct { + Items any `json:"items"` + NextAfter string `json:"next_after"` +} + +type tagList struct { + Items []service.TagCount `json:"items"` +} + +func catalogPage(ctx context.Context, rows []service.Summary, auth *sso.Handler) repoCatalog { + page := repoCatalog{Items: viewCatalog(ctx, rows, auth)} + if len(rows) == catalogPageSize { + page.NextAfter = rows[len(rows)-1].ID + } + return page +} + func viewCatalog(ctx context.Context, rows []service.Summary, auth *sso.Handler) any { if auth == nil || (identity.UserID(ctx) == "" && !identity.IsAdmin(ctx)) { return rows diff --git a/internal/httpserver/runtime.go b/internal/httpserver/runtime.go index 7a943e0..81e47be 100644 --- a/internal/httpserver/runtime.go +++ b/internal/httpserver/runtime.go @@ -495,7 +495,12 @@ func runtime(c config.Config, log *slog.Logger, s *service.Service, token string q := r.URL.Query() hours, _ := strconv.Atoi(q.Get("hours")) limit, _ := strconv.Atoi(q.Get("limit")) - result = s.ServiceLogs(service.ServiceLogQuery{Hours: hours, Level: q.Get("level"), Limit: limit, Msg: q.Get("msg")}) + switch q.Get("category") { + case "", "service", "access": + result = s.ServiceLogs(service.ServiceLogQuery{Hours: hours, Level: q.Get("level"), Limit: limit, Msg: q.Get("msg"), Access: q.Get("category") == "access", Contains: q.Get("contains")}) + default: + err = contract.Fail("INVALID_QUERY_PARAMETERS", "category must be service or access.", 400) + } } case Prefix + "/api/admin/v1/statistics": if method("GET") { @@ -539,6 +544,25 @@ func runtime(c config.Config, log *slog.Logger, s *service.Service, token string if method("GET") { result, err = s.Tags(r.Context()) } + case Prefix + "/v1/tag/list": + // /v1/tags as an object, for contracts that cannot carry a top-level array. + if method("GET") { + var tags []service.TagCount + if tags, err = s.Tags(r.Context()); err == nil { + if tags == nil { + tags = []service.TagCount{} + } + result = tagList{Items: tags} + } + } + case Prefix + "/v1/repo/catalog": + // /v1/repos as an object with the next page's cursor. + if method("GET") { + var rows []service.Summary + if rows, err = s.Catalog(r.Context(), r.URL.Query().Get("after")); err == nil { + result = catalogPage(r.Context(), rows, browserAuth) + } + } case Prefix + "/v1/tags/rename": if method("POST") { var q struct { diff --git a/internal/httpserver/service_logs.go b/internal/httpserver/service_logs.go index 2115503..e33a979 100644 --- a/internal/httpserver/service_logs.go +++ b/internal/httpserver/service_logs.go @@ -4,4 +4,4 @@ package httpserver // instance (warnings and errors by default) without a shell on the hosts. const serviceLogsPath = Prefix + "/api/admin/v1/logs" -var serviceLogParameters = map[string]bool{"hours": true, "level": true, "limit": true, "msg": true} +var serviceLogParameters = map[string]bool{"hours": true, "level": true, "limit": true, "msg": true, "category": true, "contains": true} diff --git a/internal/httpserver/website_access.go b/internal/httpserver/website_access.go index 3796d43..36ed198 100644 --- a/internal/httpserver/website_access.go +++ b/internal/httpserver/website_access.go @@ -25,7 +25,7 @@ var refsParameters = map[string]bool{"kind": true, "query": true, "author": true func publicRead(r *http.Request) bool { if r.Method == "GET" { switch r.URL.Path { - case Prefix + "/v1/repo/plugins", Prefix + "/v1/capabilities", Prefix + "/v1/code-sources", Prefix + "/v1/repos", Prefix + "/v1/tags", Prefix + "/v1/repo/availability", Prefix + "/v1/repo/refs", Prefix + "/v1/repo/commits", Prefix + "/api/admin/v1/repos", Prefix + "/api/admin/v1/repo", Prefix + "/api/admin/v1/statistics", Prefix + "/api/admin/v1/cluster", Prefix + "/api/admin/v1/instances": + case Prefix + "/v1/repo/plugins", Prefix + "/v1/capabilities", Prefix + "/v1/code-sources", Prefix + "/v1/repos", Prefix + "/v1/tags", Prefix + "/v1/repo/catalog", Prefix + "/v1/tag/list", Prefix + "/v1/repo/availability", Prefix + "/v1/repo/refs", Prefix + "/v1/repo/commits", Prefix + "/api/admin/v1/repos", Prefix + "/api/admin/v1/repo", Prefix + "/api/admin/v1/statistics", Prefix + "/api/admin/v1/cluster", Prefix + "/api/admin/v1/instances": return true } } diff --git a/internal/mcpserver/manage.go b/internal/mcpserver/manage.go index 548060b..0fd4cb2 100644 --- a/internal/mcpserver/manage.go +++ b/internal/mcpserver/manage.go @@ -150,6 +150,8 @@ type siteAdminInput struct { Hours int `json:"hours,omitempty" jsonschema:"logs: window in hours (1-336, default 24)."` Level string `json:"level,omitempty" jsonschema:"logs: lowest level: warn (default), error or info."` Msg string `json:"msg,omitempty" jsonschema:"logs: only lines whose message contains this text."` + Contains string `json:"contains,omitempty" jsonschema:"logs: only lines containing this text anywhere, e.g. a request id."` + Access bool `json:"access,omitempty" jsonschema:"logs: read the request log (one line per request: route, method, status, duration) instead of the service log."` ClearSuccess bool `json:"success,omitempty" jsonschema:"clear_jobs: remove finished successful jobs."` ClearFailed bool `json:"failed,omitempty" jsonschema:"clear_jobs: remove finished failed jobs."` Window int `json:"window,omitempty" jsonschema:"statistics: minutes (15-44640)."` @@ -363,6 +365,12 @@ func registerManagement(server *mcp.Server, api API) { if in.Msg != "" { q.Set("msg", in.Msg) } + if in.Contains != "" { + q.Set("contains", in.Contains) + } + if in.Access { + q.Set("category", "access") + } return c.do("GET", "/api/admin/v1/logs", q, nil, nil) } return nil, fmt.Errorf("unknown action") diff --git a/internal/mcpserver/partial_reasons_test.go b/internal/mcpserver/partial_reasons_test.go new file mode 100644 index 0000000..f9279f7 --- /dev/null +++ b/internal/mcpserver/partial_reasons_test.go @@ -0,0 +1,24 @@ +package mcpserver + +import ( + "strings" + "testing" +) + +// The search text carries why a result is partial and what to do next. +func TestSearchTextExplainsPartial(t *testing.T) { + response := map[string]any{ + "Meta": map[string]any{"Status": "partial", "Partial": true, "PartialReasons": []string{"deadline"}, "Hint": "The search reached its time limit with 9465 candidate files unchecked.", "Coverage": map[string]any{}}, + "Result": map[string]any{"Files": []any{}, "FileCount": 0}, + } + got := searchText(response) + for _, want := range []string{`PartialReasons: ["deadline"]`, "Hint: The search reached its time limit with 9465 candidate files unchecked."} { + if !strings.Contains(got, want) { + t.Fatalf("missing %q in %s", want, got) + } + } + complete := map[string]any{"Meta": map[string]any{"Status": "ok", "Partial": false, "Coverage": map[string]any{}}, "Result": map[string]any{"Files": []any{}}} + if strings.Contains(searchText(complete), "PartialReasons") { + t.Fatal("complete result shows partial reasons") + } +} diff --git a/internal/mcpserver/search_text.go b/internal/mcpserver/search_text.go index 5ba69a8..15fd22c 100644 --- a/internal/mcpserver/search_text.go +++ b/internal/mcpserver/search_text.go @@ -79,6 +79,12 @@ func searchTextWithOptions(value any, options searchInput) string { } filesOnly := options.Output == "files" || meta["FilesOnly"] == true b.add(fmt.Sprintf("Repository: %s\nCommit: %s\nStatus: %s\nPartial: %s\nTruncated: %s\n", jsonText(meta["Repository"]), jsonText(meta["Commit"]), jsonText(meta["Status"]), jsonText(meta["Partial"]), jsonText(meta["Truncated"]))) + if reasons, ok := meta["PartialReasons"]; ok { + b.add("PartialReasons: " + jsonText(reasons) + "\n") + if hint, _ := meta["Hint"].(string); hint != "" { + b.add("Hint: " + hint + "\n") + } + } if h, ok := meta["ServedHead"].(*contract.ServedHead); ok { b.add(servedHeadText(h)) } diff --git a/internal/mcpserver/site_admin_test.go b/internal/mcpserver/site_admin_test.go index 95253f7..2260e68 100644 --- a/internal/mcpserver/site_admin_test.go +++ b/internal/mcpserver/site_admin_test.go @@ -27,6 +27,7 @@ func TestSiteAdminQueryErrorsAndLogs(t *testing.T) { {map[string]any{"action": "query_errors", "after": "c1", "repo": "org/app", "limit": 20}, "GET /api/admin/settings/query-errors", url.Values{"after": {"c1"}, "repo": {"org/app"}, "limit": {"20"}}}, {map[string]any{"action": "logs"}, "GET /api/admin/v1/logs", url.Values{}}, {map[string]any{"action": "logs", "hours": 6, "level": "error", "limit": 100, "msg": "sync failed"}, "GET /api/admin/v1/logs", url.Values{"hours": {"6"}, "level": {"error"}, "limit": {"100"}, "msg": {"sync failed"}}}, + {map[string]any{"action": "logs", "access": true, "contains": "L-1"}, "GET /api/admin/v1/logs", url.Values{"category": {"access"}, "contains": {"L-1"}}}, } { res, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "site_admin", Arguments: tc.args}) if err != nil || res.IsError { diff --git a/internal/service/hybrid_counts_test.go b/internal/service/hybrid_counts_test.go new file mode 100644 index 0000000..68cb5ef --- /dev/null +++ b/internal/service/hybrid_counts_test.go @@ -0,0 +1,80 @@ +package service + +import ( + "strings" + "testing" + + "github.com/context4ai/sourcegraph/internal/control" + "github.com/context4ai/sourcegraph/internal/gitstore" + "github.com/context4ai/sourcegraph/internal/unindexed" + "github.com/context4ai/sourcegraph/internal/zoektclient" +) + +// The review's "ReturnedFiles: 4; FileCount: 0; MatchCount: 0": a hybrid +// answer whose base files went through symlink merging (Via) had its counts +// written as Go ints, which the hybrid merge read as 0. +func TestHybridMergeKeepsLinkMergedCounts(t *testing.T) { + target := zoektclient.Target{Repo: "org/repo", Commit: "1111111111111111111111111111111111111111", RepositoryID: 1} + links := &gitstore.LinkSnapshot{Format: 1, Followed: true, Links: map[string]gitstore.LinkInfo{".claude/skills/a.md": {Target: ".agents/skills/a.md", TargetKind: "file", BlobOID: "oid"}}} + scopes := []selectedScope{{version: control.Version{Links: links}}} + line := map[string]any{"LineNumber": float64(1), "LineFragments": []any{map[string]any{"LineOffset": float64(0), "MatchLength": float64(3)}}} + files := []any{} + for _, p := range []string{".claude/skills/a.md", ".agents/skills/a.md", "knowledge/b.md", "knowledge/c.md", "knowledge/d.md"} { + files = append(files, map[string]any{"FileName": p, "Repository": target.EngineName(), "LineMatches": []any{line}}) + } + native := map[string]any{"Files": files, "FileCount": float64(5), "MatchCount": float64(5)} + if err := canonicalSearchFiles(native, []zoektclient.Target{target}, scopes); err != nil { + t.Fatal(err) + } + base := map[string]any{"Result": native, "Meta": map[string]any{"Status": "ok", "Partial": false, "Truncated": false}} + plan := &hybridPlan{target: control.Version{Commit: target.Commit}} + out, err := mergeHybrid(base, unindexed.Result{Stats: unindexed.Stats{StopReason: "complete"}}, plan, false) + if err != nil { + t.Fatal(err) + } + result := out.(map[string]any)["Result"].(map[string]any) + if n := len(result["Files"].([]any)); n != 4 || number(result["FileCount"]) != 4 || number(result["MatchCount"]) != 4 { + t.Fatalf("%d files, FileCount %v, MatchCount %v", n, result["FileCount"], result["MatchCount"]) + } +} + +func TestNumberReadsIntAndFloat(t *testing.T) { + for _, v := range []any{4, int64(4), 4.0} { + if number(v) != 4 { + t.Fatalf("%T", v) + } + } + if number(nil) != 0 || number("4") != 0 { + t.Fatal("non-numbers must read 0") + } +} + +// A hybrid answer whose scan of the changed files stopped early, or whose +// merged matches reach the budget, says why (the base index answer was complete). +func TestHybridPartialReasons(t *testing.T) { + plan := &hybridPlan{target: control.Version{Commit: "1111111111111111111111111111111111111111"}} + for _, c := range []struct { + stop string + matches float64 + want []string + }{ + {"deadline", 1, []string{PartialScanStopped}}, + {"complete", 10000, []string{PartialMatchLimit}}, + {"complete", 1, nil}, + } { + base := map[string]any{"Result": map[string]any{"Files": []any{}, "FileCount": 0.0, "MatchCount": c.matches}, "Meta": map[string]any{"Status": "ok", "Partial": false}} + out, err := mergeHybrid(base, unindexed.Result{Stats: unindexed.Stats{StopReason: c.stop}}, plan, false) + if err != nil { + t.Fatal(err) + } + meta := out.(map[string]any)["Meta"].(map[string]any) + reasons, _ := meta["PartialReasons"].([]string) + hint, _ := meta["Hint"].(string) + if len(reasons) != len(c.want) || (len(c.want) > 0 && (reasons[0] != c.want[0] || meta["Partial"] != true || hint == "")) || (len(c.want) == 0 && meta["Partial"] != false) { + t.Fatalf("%s/%v: %v", c.stop, c.matches, meta) + } + if c.stop == "deadline" && !strings.Contains(hint, "scan stopped early (deadline)") { + t.Fatal(hint) + } + } +} diff --git a/internal/service/hybrid_search.go b/internal/service/hybrid_search.go index 5fd361e..ea97dd6 100644 --- a/internal/service/hybrid_search.go +++ b/internal/service/hybrid_search.go @@ -8,6 +8,7 @@ import ( "fmt" "log/slog" "path" + "slices" "sort" "strings" "sync" @@ -761,12 +762,25 @@ func mergeHybrid(baseOut any, delta unindexed.Result, p *hybridPlan, filesOnly b } files = append(files, m) } - num := func(k string) float64 { n, _ := native[k].(float64); return n } + num := func(k string) float64 { return number(native[k]) } fileCount := num("FileCount") + float64(delta.FileCount) matchCount := num("MatchCount") + float64(delta.MatchCount) native["Files"], native["FileCount"], native["MatchCount"] = files, fileCount, matchCount partial, _ := meta["Partial"].(bool) - partial = partial || delta.Stats.StopReason != "complete" || matchCount >= 10000 + reasons, _ := meta["PartialReasons"].([]string) + if delta.Stats.StopReason != "complete" && !slices.Contains(reasons, PartialScanStopped) { + reasons = append(reasons, PartialScanStopped) + } + if matchCount >= 10000 && !slices.Contains(reasons, PartialMatchLimit) { + reasons = append(reasons, PartialMatchLimit) + } + partial = partial || len(reasons) > 0 + if len(reasons) > 0 { + meta["PartialReasons"] = reasons + if _, ok := meta["Hint"]; !ok || delta.Stats.StopReason != "complete" { + meta["Hint"] = hybridHint(reasons, delta.Stats.StopReason, native) + } + } truncated, _ := meta["Truncated"].(bool) truncated = truncated || fileCount > float64(len(files)) || (!filesOnly && matchCount > float64(shown)) state := "ok" @@ -933,3 +947,12 @@ func (g *hybridGroup) do(ctx context.Context, key string, fn func() (any, error) return nil, ctx.Err() } } + +// hybridHint explains a partial hybrid answer; a stopped scan of the changed +// files comes first because it is specific to hybrid search. +func hybridHint(reasons []string, stop string, native map[string]any) string { + if slices.Contains(reasons, PartialScanStopped) { + return "The files changed since the indexed commit were scanned and the scan stopped early (" + stop + "); changed files after that point were not searched. Narrow paths or globs, or search again once this commit is indexed." + } + return partialHint(reasons, native) +} diff --git a/internal/service/link_review_test.go b/internal/service/link_review_test.go index 56254b0..043f102 100644 --- a/internal/service/link_review_test.go +++ b/internal/service/link_review_test.go @@ -72,7 +72,7 @@ func TestCanonicalFilesOnlyCounts(t *testing.T) { if err := canonicalSearchFiles(result, []zoektclient.Target{target}, []selectedScope{{version: control.Version{Links: m}}}); err != nil { t.Fatal(err) } - if result["FileCount"] != 1 { + if result["FileCount"] != 1.0 { // float64, like decoded engine counts t.Fatal(result) } if _, exists := result["MatchCount"]; exists { diff --git a/internal/service/link_search.go b/internal/service/link_search.go index bdfff80..5829f4d 100644 --- a/internal/service/link_search.go +++ b/internal/service/link_search.go @@ -99,7 +99,9 @@ func canonicalSearchFiles(native map[string]any, targets []zoektclient.Target, s } native["Files"] = result if mergedAny { - native["FileCount"] = len(result) + // JSON numbers decode as float64; keep that type so later merges + // (hybrid search) read these counts instead of 0. + native["FileCount"] = float64(len(result)) hasLines := false for _, f := range merged { if _, ok := f["LineMatches"]; ok { @@ -108,7 +110,7 @@ func canonicalSearchFiles(native map[string]any, targets []zoektclient.Target, s } } if hasLines { - native["MatchCount"] = matches + native["MatchCount"] = float64(matches) } else { delete(native, "MatchCount") } @@ -218,3 +220,17 @@ func linkObjects(m *gitstore.LinkSnapshot) (map[string]string, error) { } return out, nil } + +// number reads a count from a decoded engine result, whether it came from +// JSON (float64) or was set in Go (int). +func number(v any) float64 { + switch n := v.(type) { + case float64: + return n + case int: + return float64(n) + case int64: + return float64(n) + } + return 0 +} diff --git a/internal/service/link_search_test.go b/internal/service/link_search_test.go index 9186db9..6bd82dd 100644 --- a/internal/service/link_search_test.go +++ b/internal/service/link_search_test.go @@ -32,7 +32,8 @@ func TestCanonicalSearchPreservesPathsAndAliases(t *testing.T) { t.Fatal(err) } out := native["Files"].([]any) - if len(out) != 2 || native["MatchCount"] != 2 { + // Counts stay float64 like the decoded engine answer (hybrid search reads them). + if len(out) != 2 || native["MatchCount"] != 2.0 || native["FileCount"] != 2.0 { t.Fatalf("%+v", native) } f := out[0].(map[string]any) diff --git a/internal/service/partial_reasons_test.go b/internal/service/partial_reasons_test.go new file mode 100644 index 0000000..5d7594e --- /dev/null +++ b/internal/service/partial_reasons_test.go @@ -0,0 +1,36 @@ +package service + +import ( + "reflect" + "strings" + "testing" +) + +// An incomplete answer names why and what to do; a complete one names nothing. +func TestPartialReasonsAndHints(t *testing.T) { + for _, c := range []struct { + name string + native map[string]any + want []string + hint string + }{ + {"complete", map[string]any{"FileCount": 3.0, "MatchCount": 5.0}, nil, ""}, + {"deadline", map[string]any{"FilesSkippedDueToCancellation": 9465.0, "FilesSkipped": 9465.0}, []string{PartialDeadline}, "9465 candidate files unchecked"}, + {"filter", map[string]any{"MoreCandidates": true, "CandidatesChecked": 300.0}, []string{PartialFilterCandidates}, "checked 300 candidate files"}, + {"match limit", map[string]any{"MatchCount": 10000.0}, []string{PartialMatchLimit}, "internal budget 10000"}, + // The engine counts a shard it never started because time ran out as + // ShardsSkipped: that is the deadline, not the match budget. + {"shards skipped at the deadline", map[string]any{"ShardsSkipped": 2.0}, []string{PartialDeadline}, "2 index shards unchecked"}, + {"shard error", map[string]any{"Crashes": 1.0}, []string{PartialEngineError}, "shard failed"}, + {"other skip", map[string]any{"FilesSkipped": 4.0}, []string{PartialSkipped}, "skipped some files"}, + {"deadline and filter", map[string]any{"FilesSkippedDueToCancellation": 10.0, "MoreCandidates": true}, []string{PartialDeadline, PartialFilterCandidates}, "time limit"}, + } { + got := partialReasons(c.native) + if !reflect.DeepEqual(got, c.want) { + t.Fatalf("%s: reasons %v want %v", c.name, got, c.want) + } + if len(got) > 0 && !strings.Contains(partialHint(got, c.native), c.hint) { + t.Fatalf("%s: hint %q lacks %q", c.name, partialHint(got, c.native), c.hint) + } + } +} diff --git a/internal/service/scoped_search.go b/internal/service/scoped_search.go index 86868a8..1054353 100644 --- a/internal/service/scoped_search.go +++ b/internal/service/scoped_search.go @@ -3,6 +3,7 @@ package service import ( "context" "encoding/json" + "fmt" "regexp" "sort" @@ -339,12 +340,13 @@ func (s *Service) runIndexedSearch(ctx context.Context, name string, r control.R // Preserve engine identity until canonicalization. } } - num := func(k string) float64 { n, _ := native[k].(float64); return n } - partial := num("Crashes") > 0 || num("FilesSkipped") > 0 || num("ShardsSkipped") > 0 || num("MatchCount") >= 10000 + num := func(k string) float64 { return number(native[k]) } displayed := 0 if files, ok := native["Files"].([]any); ok { displayed = len(files) } + reasons := partialReasons(native) + partial := len(reasons) > 0 responseTruncated, _ := native["ResponseTruncated"].(bool) filesOnly, _ := native["ResponseFilesOnly"].(bool) delete(native, "ResponseTruncated") @@ -365,6 +367,10 @@ func (s *Service) runIndexedSearch(ctx context.Context, name string, r control.R } } meta := map[string]any{"Protocol": "zoekt-single-repo-v1", "Status": state, "Partial": partial, "Truncated": truncated, "Commit": v.Commit, "Repository": name, "Coverage": map[string]any{"Profile": "text-no-ctags", "IndexedDocuments": docs, "CompleteRepository": false, "IndexMode": r.EffectiveIndexMode(), "Paths": coverage, "Groups": groups}} + if partial { + meta["PartialReasons"] = reasons + meta["Hint"] = partialHint(reasons, native) + } for k, value := range linkCoverage(scopes) { meta["Coverage"].(map[string]any)[k] = value } @@ -374,6 +380,10 @@ func (s *Service) runIndexedSearch(ctx context.Context, name string, r control.R if e := canonicalSearchFiles(native, targets, scopes); e != nil { return nil, e } + // Never report fewer files than the answer holds. + if files, ok := native["Files"].([]any); ok && number(native["FileCount"]) < float64(len(files)) { + native["FileCount"] = float64(len(files)) + } if filesOnly { meta["FilesOnly"] = true } @@ -383,3 +393,60 @@ func (s *Service) runIndexedSearch(ctx context.Context, name string, r control.R } return map[string]any{"Result": native, "Meta": meta}, nil } + +// Partial reasons of an indexed search (Meta.PartialReasons). +const ( + PartialDeadline = "deadline" // the engine's time limit stopped it before every candidate file or shard was checked + PartialMatchLimit = "match_limit" // the internal match budget (10000) was reached + PartialEngineError = "engine_error" // an index shard failed + PartialFilterCandidates = "filter_candidates" // word-boundary or glob verification left engine candidates unchecked + PartialSkipped = "files_skipped" // the engine skipped files for another limit + PartialScanStopped = "scan_stopped" // hybrid search: the scan of files changed since the index stopped early +) + +// partialReasons says why an engine answer is incomplete; none means complete +// within the engine's limits (not that the whole repository was covered). +func partialReasons(native map[string]any) []string { + num := func(k string) float64 { return number(native[k]) } + var out []string + if num("Crashes") > 0 { + out = append(out, PartialEngineError) + } + // The engine counts a shard it never started because the time ran out + // as ShardsSkipped: a deadline, not the match budget. + if num("FilesSkippedDueToCancellation") > 0 || num("ShardsSkipped") > 0 { + out = append(out, PartialDeadline) + } + if num("MatchCount") >= 10000 { + out = append(out, PartialMatchLimit) + } + if more, _ := native["MoreCandidates"].(bool); more { + out = append(out, PartialFilterCandidates) + } + if len(out) == 0 && num("FilesSkipped") > 0 { + out = append(out, PartialSkipped) + } + return out +} + +// partialHint tells the caller what to do with an incomplete answer. +func partialHint(reasons []string, native map[string]any) string { + num := func(k string) float64 { return number(native[k]) } + for _, r := range reasons { + switch r { + case PartialDeadline: + unchecked := fmt.Sprintf("%d candidate files", int(num("FilesSkippedDueToCancellation"))) + if num("FilesSkippedDueToCancellation") == 0 { + unchecked = fmt.Sprintf("%d index shards", int(num("ShardsSkipped"))) + } + return "The search reached its time limit with " + unchecked + " unchecked, so results can differ between runs and missing files are not absent. Narrow it: add paths or -g globs, use a fixed string (-F) or a more specific term." + case PartialFilterCandidates: + return fmt.Sprintf("Word-boundary or glob verification checked %d candidate files and more remain unchecked; missing files are not absent. Narrow it with paths or -g globs, or search the terms separately.", int(num("CandidatesChecked"))) + case PartialMatchLimit: + return "Too many matches (internal budget 10000); results are incomplete. Use a more specific pattern or narrow paths." + case PartialEngineError: + return "An index shard failed during the search; retry, and report it if it repeats." + } + } + return "The engine skipped some files; results are incomplete. Narrow paths or the pattern." +} diff --git a/internal/service/search_partial_test.go b/internal/service/search_partial_test.go new file mode 100644 index 0000000..d6897d1 --- /dev/null +++ b/internal/service/search_partial_test.go @@ -0,0 +1,53 @@ +package service + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/context4ai/sourcegraph/internal/contract" + "github.com/context4ai/sourcegraph/internal/control" + "github.com/context4ai/sourcegraph/internal/zoektclient" +) + +// A search the engine stopped at its deadline answers Partial with the reason +// and a hint, and never reports fewer files than it returns (the report's +// "ReturnedFiles 4; FileCount 0"). +func TestSearchExplainsDeadlinePartial(t *testing.T) { + sha := strings.Repeat("a", 40) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/list" { + json.NewEncoder(w).Encode(map[string]any{"List": map[string]any{"Repos": []any{map[string]any{"Repository": map[string]any{"ID": 7, "Name": "snapshot/7", "Branches": []any{map[string]any{"Name": "snapshot", "Version": sha}}}, "Stats": map[string]any{"Shards": 1, "Documents": 1}}}}}) + return + } + var files []any + for _, name := range []string{"a.md", "b.md", "c.md", "d.md"} { + files = append(files, map[string]any{"Repository": "snapshot/7", "RepositoryID": 7, "Version": sha, "FileName": name, "LineMatches": []any{map[string]any{"LineNumber": 1, "Line": "bXVzdCBlYXQ="}}}) + } + json.NewEncoder(w).Encode(map[string]any{"Result": map[string]any{"Files": files, "FileCount": 0, "MatchCount": 0, "FilesSkipped": 7542, "FilesSkippedDueToCancellation": 7542}}) + })) + defer server.Close() + engine, err := zoektclient.New(server.URL) + if err != nil { + t.Fatal(err) + } + defer engine.Close() + s := &Service{Engine: engine, DB: searchBudgetStore{repo: control.Repository{Name: "org/repo", Enabled: true, Versions: []control.Version{{Commit: sha, Generation: 7, Shards: 1, Files: 1}}}}} + value, err := s.Search(context.Background(), "org/repo", contract.SearchRequest{Revision: sha, Pattern: "must.?eat", IgnoreCase: true}) + if err != nil { + t.Fatal(err) + } + out := value.(map[string]any) + meta, result := out["Meta"].(map[string]any), out["Result"].(map[string]any) + reasons, _ := meta["PartialReasons"].([]string) + hint, _ := meta["Hint"].(string) + if meta["Status"] != "partial" || meta["Partial"] != true || len(reasons) != 1 || reasons[0] != PartialDeadline || !strings.Contains(hint, "7542 candidate files unchecked") { + t.Fatalf("meta %v", meta) + } + if result["FileCount"] != 4.0 || len(result["Files"].([]any)) != 4 { + t.Fatalf("FileCount %v for %d files", result["FileCount"], len(result["Files"].([]any))) + } +} diff --git a/internal/service/service_logs.go b/internal/service/service_logs.go index e896ab7..9cc9ea1 100644 --- a/internal/service/service_logs.go +++ b/internal/service/service_logs.go @@ -18,6 +18,11 @@ type ServiceLogQuery struct { Level string // lowest level: "info", "warn" (default) or "error" Limit int // newest lines returned, 1 to 5000 Msg string // optional: only lines whose message contains this text + // Access reads the access log (one line per request, level info) instead + // of the run log; the default level is then info. + Access bool + // Contains keeps only lines whose raw JSON contains this text (e.g. a request id). + Contains string } type logSummary struct { @@ -45,6 +50,13 @@ func (s *Service) ServiceLogs(q ServiceLogQuery) map[string]any { min, ok := logLevels[strings.ToUpper(q.Level)] if !ok || strings.EqualFold(q.Level, "debug") { min = logLevels["WARN"] + if q.Access { + min = logLevels["INFO"] + } + } + category := naslog.Service + if q.Access { + category = naslog.Access } now := s.now() from := now.Add(-time.Duration(q.Hours) * time.Hour) @@ -57,7 +69,7 @@ func (s *Service) ServiceLogs(q ServiceLogQuery) map[string]any { var lines []entry summary := map[string]*logSummary{} scanned := 0 - base := naslog.Dir(s.Root, naslog.Service) + base := naslog.Dir(s.Root, category) dirs, _ := os.ReadDir(base) for _, d := range dirs { if !d.IsDir() { @@ -65,6 +77,9 @@ func (s *Service) ServiceLogs(q ServiceLogQuery) map[string]any { } readLines(filepath.Join(base, d.Name()), days, func(raw []byte) { scanned++ + if q.Contains != "" && !strings.Contains(string(raw), q.Contains) { + return + } var line map[string]any if json.Unmarshal(raw, &line) != nil { return @@ -116,7 +131,7 @@ func (s *Service) ServiceLogs(q ServiceLogQuery) map[string]any { }) return map[string]any{ "from": from.UTC().Format(time.RFC3339), "to": now.UTC().Format(time.RFC3339), - "level": strings.ToLower(levelName(min)), "scanned_lines": scanned, + "level": strings.ToLower(levelName(min)), "scanned_lines": scanned, "category": category, "summary": sums, "lines": out, "truncated": truncated, } } diff --git a/internal/service/service_logs_test.go b/internal/service/service_logs_test.go index 722c013..24e887c 100644 --- a/internal/service/service_logs_test.go +++ b/internal/service/service_logs_test.go @@ -56,3 +56,30 @@ func TestServiceLogsFiltersAndSummarizes(t *testing.T) { t.Fatalf("72 h window: %v", l) } } + +func TestServiceLogsReadsTheAccessLogByRequestID(t *testing.T) { + root := t.TempDir() + now := time.Now().UTC() + dir := filepath.Join(naslog.Dir(root, naslog.Access), "a") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + lines := `{"time":"` + now.Add(-time.Minute).Format(time.RFC3339Nano) + `","level":"INFO","msg":"request","route":"/v1/","request_id":"R-1","status":200}` + "\n" + + `{"time":"` + now.Format(time.RFC3339Nano) + `","level":"INFO","msg":"request","route":"/api/","request_id":"R-2"}` + "\n" + if err := os.WriteFile(filepath.Join(dir, naslog.Day(now)), []byte(lines), 0o644); err != nil { + t.Fatal(err) + } + s := &Service{Root: root} + // The run log has none of these lines; the access log defaults to level info. + if l := s.ServiceLogs(ServiceLogQuery{Hours: 1, Level: "info"})["lines"].([]map[string]any); len(l) != 0 { + t.Fatalf("run log: %v", l) + } + got := s.ServiceLogs(ServiceLogQuery{Hours: 1, Access: true, Contains: `"request_id":"R-1"`}) + l := got["lines"].([]map[string]any) + if got["category"] != naslog.Access || len(l) != 1 || l[0]["request_id"] != "R-1" { + t.Fatalf("access by request id: %v", got) + } + if l := s.ServiceLogs(ServiceLogQuery{Hours: 1, Access: true})["lines"].([]map[string]any); len(l) != 2 { + t.Fatalf("all access lines: %v", l) + } +} diff --git a/internal/sitesettings/github_proxy_test.go b/internal/sitesettings/github_proxy_test.go index 7e9b90a..f5ced8e 100644 --- a/internal/sitesettings/github_proxy_test.go +++ b/internal/sitesettings/github_proxy_test.go @@ -77,8 +77,18 @@ func TestMongoStoreLoadsAllSections(t *testing.T) { t.Fatal(err) } records, err := store.Load(ctx) - if err != nil || len(records) != 5 { - t.Fatalf("loaded %d sections: %v", len(records), err) + sections := []string{RepositoryDefaultsName, AccessName, CodeSourceName, AppearanceName, GitHubProxyName, StorageName, ReaderPrepareName} + if err != nil || len(records) != len(sections) { + t.Fatalf("loaded %d sections, want %d: %v", len(records), len(sections), err) + } + loaded := map[string]bool{} + for _, r := range records { + loaded[r.Name] = true + } + for _, name := range sections { + if !loaded[name] { + t.Fatalf("section %s not loaded: %v", name, loaded) + } } raw, _ := json.Marshal(map[string]any{"enabled": true, "env": exampleProxyEnv}) if _, err := s.Update(ctx, GitHubProxyName, s.Snapshot().GitHubProxy.Revision, raw, "admin"); err != nil { diff --git a/internal/zoektclient/client.go b/internal/zoektclient/client.go index a4cd8d8..36f7979 100644 --- a/internal/zoektclient/client.go +++ b/internal/zoektclient/client.go @@ -23,6 +23,40 @@ import ( ) const MaxResponseBytes = 2 << 20 + +// EngineWallTime bounds one engine search. With 1 s a broad regular +// expression over a monorepo checked a fraction of its candidates and gave a +// different partial result each run. 2 s leaves room for further candidate +// pages within searchDeadline, and bounds how long a search holds an engine +// slot and the service's read lock (writers queue behind it). All attempts and +// filter pages of one request share searchDeadline. +const EngineWallTime = 2 * time.Second + +const searchDeadline = 5 * time.Second + +// engineMatchBudget is the engine's internal match budget (shard and total): +// a MatchCount at or above it means the engine stopped before searching every +// candidate. +const engineMatchBudget = 10000 + +// maxFilterPages bounds how many candidate pages a post-filter (Unicode word +// boundary, byte globs) checks for one request. +const maxFilterPages = 5 + +// wallTime is the engine budget left for one attempt within ctx. +func wallTime(ctx context.Context) time.Duration { + wall := EngineWallTime + if deadline, ok := ctx.Deadline(); ok { + if left := time.Until(deadline) - 200*time.Millisecond; left < wall { + wall = left + } + } + if wall < 100*time.Millisecond { + wall = 100 * time.Millisecond + } + return wall +} + const MaxQueryBytes = 8192 // Generated queries spell out Unicode classes and glob filters, so they may @@ -59,9 +93,9 @@ func New(endpoint string) (*Client, error) { return nil, errors.New("engine endpoint must use a loopback IP and explicit port") } transport := &http.Transport{Proxy: nil, MaxIdleConns: 8, MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, - DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, ResponseHeaderTimeout: 3 * time.Second} + DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, ResponseHeaderTimeout: searchDeadline} return &Client{endpoint: strings.TrimSuffix(endpoint, "/") + "/api/search", http: &http.Client{ - Transport: transport, Timeout: 5 * time.Second, + Transport: transport, Timeout: searchDeadline, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("engine redirects are disabled") }, }}, nil } @@ -130,7 +164,7 @@ func (c *Client) SearchManyWithOptions(ctx context.Context, targets []Target, qu } // Only oversized responses are retried. All attempts retain the same pinned // targets and share a deadline, so fallback cannot turn into unbounded work. - ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + ctx, cancel := context.WithTimeout(ctx, searchDeadline) defer cancel() budgets := []displayBudget{{100, 1000, 2, false}, {20, 100, 0, false}, {100, 1000, 0, true}} if options.FilesOnly { @@ -149,6 +183,7 @@ func (c *Client) SearchManyWithOptions(ctx context.Context, targets []Target, qu return nil, err } if filter.active() { + raw := result result, err = filter.apply(ctx, result) if errors.As(err, &ce) && ce.Code == "ENGINE_RESPONSE_TOO_LARGE" { continue @@ -156,6 +191,9 @@ func (c *Client) SearchManyWithOptions(ctx context.Context, targets []Target, qu if err != nil { return nil, err } + if result, err = c.filterMore(ctx, identities, ids, query, budget, options.ExcludePaths, filter, raw, result); err != nil { + return nil, err + } } if options.FilesOnly { budget.filesOnly = true @@ -234,7 +272,7 @@ func (c *Client) searchAttempt(ctx context.Context, identities map[uint32]Target func (c *Client) searchRaw(ctx context.Context, ids []uint32, query string, budget displayBudget, exclude []string) ([]byte, error) { if c.local != nil { - data, err := c.local.searchExcluding(ctx, ids, query, exclude, &zoekt.SearchOptions{MaxWallTime: time.Second, MaxDocDisplayCount: budget.files, ShardMaxMatchCount: 10000, TotalMaxMatchCount: 10000, MaxMatchDisplayCount: budget.matches, NumContextLines: budget.contextLines}) + data, err := c.local.searchExcluding(ctx, ids, query, exclude, &zoekt.SearchOptions{MaxWallTime: wallTime(ctx), MaxDocDisplayCount: budget.files, ShardMaxMatchCount: engineMatchBudget, TotalMaxMatchCount: engineMatchBudget, MaxMatchDisplayCount: budget.matches, NumContextLines: budget.contextLines}) if err != nil { if ctx.Err() != nil { return nil, ctx.Err() @@ -261,8 +299,8 @@ func (c *Client) searchRaw(ctx context.Context, ids []uint32, query string, budg RepoIDs []uint32 Opts map[string]any }{query, ids, map[string]any{ - "MaxWallTime": int64(time.Second), "MaxDocDisplayCount": budget.files, - "ShardMaxMatchCount": 10000, "TotalMaxMatchCount": 10000, + "MaxWallTime": int64(wallTime(ctx)), "MaxDocDisplayCount": budget.files, + "ShardMaxMatchCount": engineMatchBudget, "TotalMaxMatchCount": engineMatchBudget, "MaxMatchDisplayCount": budget.matches, "NumContextLines": budget.contextLines, }}) req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body)) diff --git a/internal/zoektclient/filter_pages.go b/internal/zoektclient/filter_pages.go new file mode 100644 index 0000000..1bca630 --- /dev/null +++ b/internal/zoektclient/filter_pages.go @@ -0,0 +1,214 @@ +package zoektclient + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/context4ai/sourcegraph/internal/contract" +) + +// rawPage is what a post-filter needs to know about one engine answer. +type rawPage struct { + names []string + fileCount int + matchCount int + cancelled int + skipped int + crashes int + shards int +} + +func readRawPage(raw json.RawMessage) rawPage { + var r struct { + Files []struct{ FileName string } + FileCount int + MatchCount int + FilesSkippedDueToCancellation int + FilesSkipped int + Crashes int + ShardsSkipped int + } + _ = json.Unmarshal(raw, &r) + p := rawPage{fileCount: r.FileCount, matchCount: r.MatchCount, cancelled: r.FilesSkippedDueToCancellation, skipped: r.FilesSkipped, crashes: r.Crashes, shards: r.ShardsSkipped} + for _, f := range r.Files { + p.names = append(p.names, f.FileName) + } + return p +} + +// more reports candidates beyond this page: matched but not returned, or not +// checked (time limit, skipped files or shards, or the match budget: the +// in-process engine stops at it without counting what it left). +func (p rawPage) more() bool { + return p.fileCount > len(p.names) || p.cancelled > 0 || p.skipped > 0 || p.shards > 0 || p.matchCount >= engineMatchBudget +} + +// stopPaging: the time ran out or the answer grew too large; keep what was +// found. A caller's cancellation is not a reason to answer. +func stopPaging(ctx context.Context, err error) (bool, error) { + if errors.Is(err, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) { + return true, context.Canceled + } + return errors.Is(err, context.DeadlineExceeded) || ctx.Err() != nil || isTooLarge(err), nil +} + +func isTooLarge(err error) bool { + var ce *contract.Error + return errors.As(err, &ce) && ce.Code == "ENGINE_RESPONSE_TOO_LARGE" +} + +// filterMore continues a post-filtered search (Unicode word boundary, byte +// globs) over further engine candidates. The engine matches a broader query +// and returns one page; when the filter drops those candidates (e.g. \bft\b +// against "left", "shift"), real matches may sit in candidates the page did +// not include. Following pages exclude every candidate already checked, until +// a page's worth of files or matched lines is found, no candidates remain, +// maxFilterPages, a page that brings nothing new, or the shared deadline. +// +// The answer counts every verified file and line found (FileCount, +// MatchCount), shows at most the display budget within MaxResponseBytes, and +// says whether engine candidates remain unchecked (MoreCandidates; partial) +// apart from verified results not shown (FileCount above the files shown; +// truncated). Engine counters of the last page describe what remains. +func (c *Client) filterMore(ctx context.Context, identities map[uint32]Target, ids []uint32, query string, budget displayBudget, exclude []string, filter *patternFilter, raw, filtered json.RawMessage) (json.RawMessage, error) { + page := readRawPage(raw) + var fields map[string]json.RawMessage + if err := json.Unmarshal(filtered, &fields); err != nil { + return nil, err + } + var first []json.RawMessage + if err := json.Unmarshal(fields["Files"], &first); err != nil { + return nil, err + } + if len(page.names) == 0 { + // Nothing returned and nothing to exclude: a repeat of the same query + // would only spend the remaining time on the same answer, and there + // is no file whose counts could be stale. + return filtered, nil + } + // Every other answer, paged or not, ends below: counts of verified files + // and lines, MoreCandidates while engine candidates remain unchecked. + kept, keptNames := []json.RawMessage{}, map[string]bool{} + lines := 0 + add := func(files []json.RawMessage) { + for _, f := range files { + var meta struct { + FileName string + LineMatches []json.RawMessage + } + _ = json.Unmarshal(f, &meta) + if keptNames[meta.FileName] { + continue + } + keptNames[meta.FileName] = true + kept = append(kept, f) + lines += len(meta.LineMatches) + } + } + add(first) + checked := map[string]bool{} + order := []string{} + for _, n := range page.names { + if !checked[n] { + checked[n] = true + order = append(order, n) + } + } + crashes, responseTruncated := page.crashes, string(fields["ResponseTruncated"]) == "true" + pages := 1 + for page.more() && len(kept) < budget.files && lines < budget.matches && pages < maxFilterPages { + if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < 300*time.Millisecond { + break + } + skip := append(append([]string{}, exclude...), order...) + if c.local == nil && len(skip) > MaxRemoteExcludePaths { + break + } + next, err := c.searchAttempt(ctx, identities, ids, query, budget, skip) + if stop, cerr := stopPaging(ctx, err); cerr != nil { + return nil, cerr + } else if stop { + break + } + if err != nil { + return nil, err + } + nextPage := readRawPage(next) + verified, err := filter.apply(ctx, next) + if stop, cerr := stopPaging(ctx, err); cerr != nil { + return nil, cerr + } else if stop { + break + } + if err != nil { + return nil, err + } + pages++ + var vf struct { + Files []json.RawMessage + ResponseTruncated bool + } + if err := json.Unmarshal(verified, &vf); err != nil { + return nil, err + } + fresh := 0 + for _, n := range nextPage.names { + if !checked[n] { + checked[n] = true + order = append(order, n) + fresh++ + } + } + add(vf.Files) + crashes += nextPage.crashes + responseTruncated = responseTruncated || vf.ResponseTruncated + page = nextPage + if fresh == 0 { + break // the engine repeats itself; stop rather than loop + } + } + total, totalLines := len(kept), lines + // Show at most the display budget of files and lines. + shown, shownLines := kept, 0 + for i, f := range kept { + var meta struct{ LineMatches []json.RawMessage } + _ = json.Unmarshal(f, &meta) + if i >= budget.files || (shownLines > 0 && shownLines+len(meta.LineMatches) > budget.matches) { + shown = kept[:i] + break + } + shownLines += len(meta.LineMatches) + } + set := func(k string, v any) { fields[k], _ = json.Marshal(v) } + set("FileCount", total) + if budget.filesOnly { + delete(fields, "MatchCount") // file-only pages carry no lines to count + } else { + set("MatchCount", totalLines) + } + // The last page's engine counters describe the candidates still unchecked. + set("FilesSkippedDueToCancellation", page.cancelled) + set("FilesSkipped", page.skipped) + set("ShardsSkipped", page.shards) + set("Crashes", crashes) + set("CandidatesChecked", len(order)) + set("FilterPages", pages) + set("MoreCandidates", page.more()) + if responseTruncated { + set("ResponseTruncated", true) + } + for { + set("Files", shown) + out, err := json.Marshal(fields) + if err != nil { + return nil, err + } + if len(out) <= MaxResponseBytes || len(shown) == 0 { + return out, nil + } + shown = shown[:len(shown)/2] + set("ResponseTruncated", true) + } +} diff --git a/internal/zoektclient/filter_pages_review_test.go b/internal/zoektclient/filter_pages_review_test.go new file mode 100644 index 0000000..12dcf54 --- /dev/null +++ b/internal/zoektclient/filter_pages_review_test.go @@ -0,0 +1,323 @@ +package zoektclient + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/sourcegraph/zoekt" +) + +type pageFile struct { + name string + lines []string +} + +// scriptedEngine answers each call with the next scripted page; files a +// query excludes (-f:) are dropped from it, like the engine would. +func scriptedEngine(target Target, pages []func() ([]pageFile, zoekt.Stats), calls *[]string) *Client { + c, _ := New("http://127.0.0.1:6070") + c.http.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + var body struct{ Q string } + json.NewDecoder(req.Body).Decode(&body) + *calls = append(*calls, body.Q) + i := len(*calls) - 1 + if i >= len(pages) { + i = len(pages) - 1 + } + files, stats := pages[i]() + q := strings.ReplaceAll(body.Q, `\`, "") + out := []zoekt.FileMatch{} + for _, f := range files { + if strings.Contains(q, "-f:") && strings.Contains(q, f.name) { + continue + } + fm := zoekt.FileMatch{Repository: target.EngineName(), RepositoryID: 7, Version: target.Commit, FileName: f.name} + for n, l := range f.lines { + fm.LineMatches = append(fm.LineMatches, zoekt.LineMatch{Line: []byte(l + "\n"), LineNumber: n + 1}) + } + out = append(out, fm) + } + data, _ := json.Marshal(map[string]any{"Result": zoekt.SearchResult{Files: out, Stats: stats}}) + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data)))}, nil + }) + return c +} + +type filtered struct { + zoekt.SearchResult + CandidatesChecked int + FilterPages int + MoreCandidates bool + ResponseTruncated bool +} + +func runFiltered(t *testing.T, c *Client, target Target, p Pattern, filesOnly bool) (filtered, json.RawMessage) { + t.Helper() + q, err := PatternQuery(p) + if err != nil { + t.Fatal(err) + } + raw, err := c.SearchManyWithOptions(context.Background(), []Target{target}, q, DisplayOptions{Pattern: &p, FilesOnly: filesOnly}) + if err != nil { + t.Fatal(err) + } + var got filtered + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + return got, raw +} + +func files(prefix string, n int, line string) []pageFile { + out := []pageFile{} + for i := 0; i < n; i++ { + out = append(out, pageFile{fmt.Sprintf("%s/%03d.ts", prefix, i), []string{line}}) + } + return out +} + +var testTarget = Target{Repo: "org/repo", Commit: strings.Repeat("a", 40), RepositoryID: 7} + +// All candidates checked, more verified files than shown: truncated, not +// partial; FileCount and MatchCount count every verified file and line. +func TestFilterCompleteButTruncatedIsNotPartial(t *testing.T) { + page1 := append(files("hit", 99, "x ft y"), pageFile{"miss/0.ts", []string{"left"}}) + page2 := files("more", 20, "x ft y") + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { return page1, zoekt.Stats{FileCount: 120, MatchCount: 120} }, + func() ([]pageFile, zoekt.Stats) { return page2, zoekt.Stats{FileCount: 20, MatchCount: 20} }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if len(got.Files) != 100 || got.FileCount != 119 || got.MatchCount != 119 || got.MoreCandidates || len(calls) != 2 { + t.Fatalf("%d calls: files %d FileCount %d MatchCount %d more %v\n%.300s", len(calls), len(got.Files), got.FileCount, got.MatchCount, got.MoreCandidates, raw) + } +} + +// Shown lines stay within the line budget across pages (the engine's own +// budget applies per page only); counts still cover every verified line. +func TestFilterPagesKeepTheLineBudget(t *testing.T) { + fifty := []string{} + for i := 0; i < 50; i++ { + fifty = append(fifty, "x ft y") + } + page2 := []pageFile{} + for i := 0; i < 30; i++ { + page2 = append(page2, pageFile{fmt.Sprintf("hit/%02d.ts", i), fifty}) + } + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"a.ts", []string{"left"}}}, zoekt.Stats{FileCount: 31, MatchCount: 1501} + }, + func() ([]pageFile, zoekt.Stats) { return page2, zoekt.Stats{FileCount: 30, MatchCount: 1500} }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + lines := 0 + for _, f := range got.Files { + lines += len(f.LineMatches) + } + if lines > 1000 || lines == 0 || got.MatchCount != 1500 || got.FileCount != 30 || len(raw) > MaxResponseBytes { + t.Fatalf("shown %d lines in %d files, MatchCount %d FileCount %d", lines, len(got.Files), got.MatchCount, got.FileCount) + } +} + +// A later page whose verified answer is too large ends paging; the files +// already found are kept instead of failing the search. +func TestFilterOversizedLaterPageKeepsEarlierResults(t *testing.T) { + long := strings.Repeat("ft ", 1300) + big := []pageFile{} + for i := 0; i < 40; i++ { + big = append(big, pageFile{fmt.Sprintf("big/%02d.ts", i), []string{long}}) + } + page1 := append(files("miss", 10, "left"), pageFile{"hit.ts", []string{"x ft y"}}) + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { return page1, zoekt.Stats{FileCount: 51, MatchCount: 51} }, + func() ([]pageFile, zoekt.Stats) { return big, zoekt.Stats{FileCount: 40, MatchCount: 40} }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if len(got.Files) != 1 || got.Files[0].FileName != "hit.ts" || !got.MoreCandidates { + t.Fatalf("%d calls: %.400s", len(calls), raw) + } +} + +// Engine counters of later pages are merged: a crash on page 2 is reported, +// and the last page's skipped counts describe what remains. +func TestFilterMergesLaterPageCounters(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return files("miss", 3, "left"), zoekt.Stats{FileCount: 6, MatchCount: 6} + }, + func() ([]pageFile, zoekt.Stats) { + return files("hit", 3, "x ft y"), zoekt.Stats{FileCount: 3, MatchCount: 3, Crashes: 1} + }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if got.Crashes != 1 || got.FileCount != 3 || got.MoreCandidates { + t.Fatalf("%.400s", raw) + } +} + +// Files skipped for the match budget (no cancellation) are more candidates. +func TestFilterPagesPastMatchBudgetSkips(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return files("miss", 3, "left"), zoekt.Stats{FileCount: 3, MatchCount: 3, FilesSkipped: 50} + }, + func() ([]pageFile, zoekt.Stats) { + return files("hit", 2, "x ft y"), zoekt.Stats{FileCount: 2, MatchCount: 2} + }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if len(calls) != 2 || got.FileCount != 2 || got.FilesSkipped != 0 { + t.Fatalf("%d calls %.400s", len(calls), raw) + } +} + +// A first page that timed out with no files is not repeated with the same +// query; it stays partial for the caller. +func TestFilterDoesNotRepeatAnEmptyTimedOutPage(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return nil, zoekt.Stats{FilesSkipped: 9000, FilesSkippedDueToCancellation: 9000} + }, + }, &calls) + got, _ := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if len(calls) != 1 || got.FilesSkippedDueToCancellation != 9000 { + t.Fatalf("%d calls", len(calls)) + } +} + +// A file the engine returns again on a later page is not shown twice. +func TestFilterDeduplicatesFiles(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"hit.ts", []string{"x ft y"}}, {"miss.ts", []string{"left"}}}, zoekt.Stats{FileCount: 4, MatchCount: 4} + }, + // The engine ignores the exclusion and repeats hit.ts with one new file. + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"hit.ts", []string{"x ft y"}}, {"new.ts", []string{"ft"}}}, zoekt.Stats{FileCount: 2, MatchCount: 2} + }, + }, &calls) + c.http.Transport = dedupTransport(c.http.Transport) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + names := map[string]int{} + for _, f := range got.Files { + names[f.FileName]++ + } + if names["hit.ts"] != 1 || names["new.ts"] != 1 || got.FileCount != 2 { + t.Fatalf("%.400s", raw) + } +} + +// dedupTransport strips the exclusion so the scripted engine repeats files. +func dedupTransport(next http.RoundTripper) http.RoundTripper { + return roundTripFunc(func(req *http.Request) (*http.Response, error) { + var body map[string]any + json.NewDecoder(req.Body).Decode(&body) + if q, ok := body["Q"].(string); ok { + if i := strings.Index(q, " -f:"); i > 0 { + body["Q"] = strings.TrimSuffix(strings.TrimPrefix(q[:i], "( "), " )") + } + } + data, _ := json.Marshal(body) + req.Body = io.NopCloser(strings.NewReader(string(data))) + return next.RoundTrip(req) + }) +} + +// Byte-glob filtering of a file-only search leaves no stale engine MatchCount. +func TestFilterFilesOnlyGlobDropsStaleMatchCount(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"src/b.ts", nil}, {"src/ab.ts", nil}}, zoekt.Stats{FileCount: 4, MatchCount: 5000} + }, + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"src/ac.ts", nil}}, zoekt.Stats{FileCount: 1, MatchCount: 7} + }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: "x", Globs: []string{"src/a?.ts"}}, true) + if got.MatchCount == 5000 || got.FileCount != 2 || len(got.Files) != 2 { + t.Fatalf("%d calls %.400s", len(calls), raw) + } +} + +// A single file-only page filtered by a byte glob reports the files it shows, +// not the engine's unfiltered FileCount or its MatchCount. +func TestFilterSinglePageFilesOnlyGlobCounts(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"src/b.ts", nil}, {"src/ab.ts", nil}}, zoekt.Stats{FileCount: 2, MatchCount: 5000} + }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: "x", Globs: []string{"src/a?.ts"}}, true) + if len(calls) != 1 || len(got.Files) != 1 || got.FileCount != 1 || strings.Contains(string(raw), `"MatchCount"`) { + t.Fatalf("%d calls %.400s", len(calls), raw) + } +} + +// A first page full by files follows the same rule as one full by lines: +// verified counts, and MoreCandidates while engine candidates remain. +func TestFilterFullFirstPageReportsUncheckedCandidates(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return files("hit", 100, "x ft y"), zoekt.Stats{FileCount: 250, MatchCount: 250} + }, + }, &calls) + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if len(calls) != 1 || len(got.Files) != 100 || got.FileCount != 100 || !got.MoreCandidates || got.CandidatesChecked != 100 { + t.Fatalf("%d calls %.400s", len(calls), raw) + } +} + +// The in-process engine stops at its match budget without counting what it +// left; that page still has more candidates, so the answer stays partial. +func TestFilterMatchBudgetMeansMoreCandidates(t *testing.T) { + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return []pageFile{{"miss.ts", []string{"left"}}}, zoekt.Stats{FileCount: 1, MatchCount: 10000} + }, + }, &calls) + c.http.Transport = dedupTransport(c.http.Transport) // the engine answers the same page again + got, raw := runFiltered(t, c, testTarget, Pattern{Text: `\bft\b`}, false) + if len(got.Files) != 0 || !got.MoreCandidates { + t.Fatalf("%d calls %.400s", len(calls), raw) + } +} + +// A caller that cancels while later pages are fetched gets its cancellation, +// not a partial answer presented as success. +func TestFilterReturnsCallerCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var calls []string + c := scriptedEngine(testTarget, []func() ([]pageFile, zoekt.Stats){ + func() ([]pageFile, zoekt.Stats) { + return files("miss", 3, "left"), zoekt.Stats{FileCount: 6, MatchCount: 6} + }, + func() ([]pageFile, zoekt.Stats) { + cancel() + return files("hit", 3, "x ft y"), zoekt.Stats{FileCount: 3, MatchCount: 3} + }, + }, &calls) + p := Pattern{Text: `\bft\b`} + q, _ := PatternQuery(p) + if _, err := c.SearchManyWithOptions(ctx, []Target{testTarget}, q, DisplayOptions{Pattern: &p}); !errors.Is(err, context.Canceled) { + t.Fatalf("cancellation swallowed: %v", err) + } +} diff --git a/internal/zoektclient/filter_pages_test.go b/internal/zoektclient/filter_pages_test.go new file mode 100644 index 0000000..e16f23e --- /dev/null +++ b/internal/zoektclient/filter_pages_test.go @@ -0,0 +1,174 @@ +package zoektclient + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/sourcegraph/zoekt" +) + +// One engine search gets 2 s (within the 5 s request deadline), not 1 s: a +// regex over a monorepo stopped after a fraction of its candidates before. +func TestEngineWallTimeIsTwoSeconds(t *testing.T) { + target := Target{Repo: "org/repo", Commit: strings.Repeat("a", 40), RepositoryID: 7} + c, _ := New("http://127.0.0.1:6070") + var wall int64 + c.http.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + var body struct{ Opts struct{ MaxWallTime int64 } } + json.NewDecoder(req.Body).Decode(&body) + wall = body.Opts.MaxWallTime + data, _ := json.Marshal(map[string]any{"Result": zoekt.SearchResult{Files: []zoekt.FileMatch{}}}) + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data)))}, nil + }) + if _, err := c.Search(context.Background(), target, "needle"); err != nil { + t.Fatal(err) + } + if time.Duration(wall) != EngineWallTime || EngineWallTime != 2*time.Second { + t.Fatalf("engine wall time %v", time.Duration(wall)) + } + // A caller with less time left gets what remains, not more. + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if w := wallTime(ctx); w > time.Second || w < 500*time.Millisecond { + t.Fatalf("wall time beyond the caller's deadline: %v", w) + } +} + +// engine fakes Zoekt for a broadened \bft\b query: each call answers the next +// page of candidates not excluded by the query's -f: term. +func pagedEngine(t *testing.T, target Target, candidates []string, lineFor func(string) string, pageSize int, cancelledFirst int, calls *[]string) *Client { + c, _ := New("http://127.0.0.1:6070") + c.http.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + var body struct{ Q string } + json.NewDecoder(req.Body).Decode(&body) + *calls = append(*calls, body.Q) + files := []zoekt.FileMatch{} + remaining := 0 + for _, name := range candidates { + if strings.Contains(strings.ReplaceAll(body.Q, `\`, ""), name) { // excluded by an earlier page (-f:^(?:a\.ts|...)$) + continue + } + remaining++ + if len(files) < pageSize { + files = append(files, zoekt.FileMatch{Repository: target.EngineName(), RepositoryID: 7, Version: target.Commit, FileName: name, LineMatches: []zoekt.LineMatch{{Line: []byte(lineFor(name) + "\n"), LineNumber: 1}}}) + } + } + stats := zoekt.Stats{FileCount: remaining, MatchCount: remaining} + if len(*calls) == 1 { + stats.FilesSkippedDueToCancellation = cancelledFirst + stats.FilesSkipped = cancelledFirst + } + data, _ := json.Marshal(map[string]any{"Result": zoekt.SearchResult{Files: files, Stats: stats}}) + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data)))}, nil + }) + return c +} + +// The reported bug: \bfeet\b|\bft\b|\bmiles?\b matched "left"/"shift" first, +// the boundary check dropped that whole page and the answer was 0 files with +// FileCount 149, although real matches existed in later candidates. +func TestBoundaryFilterChecksFurtherCandidates(t *testing.T) { + target := Target{Repo: "org/repo", Commit: strings.Repeat("a", 40), RepositoryID: 7} + var candidates []string + for i := 0; i < 130; i++ { + candidates = append(candidates, fmt.Sprintf("noise/%03d.ts", i)) + } + candidates = append(candidates, "geo/distance.ts") + line := func(name string) string { + if name == "geo/distance.ts" { + return "const unit = 'ft' // 3 miles" + } + return "shiftLeft()" + } + var calls []string + c := pagedEngine(t, target, candidates, line, 100, 0, &calls) + p := Pattern{Text: `\bfeet\b|\bft\b|\bmiles?\b`, IgnoreCase: true} + q, err := PatternQuery(p) + if err != nil { + t.Fatal(err) + } + raw, err := c.SearchManyWithOptions(context.Background(), []Target{target}, q, DisplayOptions{Pattern: &p}) + if err != nil { + t.Fatal(err) + } + var got struct { + zoekt.SearchResult + CandidatesChecked int + FilterPages int + MoreCandidates bool + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + if len(got.Files) != 1 || got.Files[0].FileName != "geo/distance.ts" || got.FileCount != 1 || got.MatchCount != 1 { + t.Fatalf("real match lost: %s", raw) + } + if got.MoreCandidates || got.CandidatesChecked != 131 || got.FilterPages != 2 || len(calls) != 2 { + t.Fatalf("paging %d calls, %s", len(calls), raw) + } + if !strings.Contains(calls[1], "noise/000") || strings.Contains(calls[0], "-f:") { + t.Fatalf("second page did not exclude the checked candidates: %q", calls[1]) + } +} + +// Paging stops at its limits and then says candidates remain unchecked, +// instead of presenting an empty page as the whole answer. +func TestBoundaryFilterReportsUncheckedCandidates(t *testing.T) { + target := Target{Repo: "org/repo", Commit: strings.Repeat("a", 40), RepositoryID: 7} + var candidates []string + for i := 0; i < 600; i++ { + candidates = append(candidates, fmt.Sprintf("noise/%03d.ts", i)) + } + var calls []string + c := pagedEngine(t, target, candidates, func(string) string { return "shiftLeft()" }, 100, 0, &calls) + p := Pattern{Text: `\bft\b`} + q, _ := PatternQuery(p) + raw, err := c.SearchManyWithOptions(context.Background(), []Target{target}, q, DisplayOptions{Pattern: &p}) + if err != nil { + t.Fatal(err) + } + var got struct { + zoekt.SearchResult + CandidatesChecked int + MoreCandidates bool + } + json.Unmarshal(raw, &got) + // A remote engine takes at most MaxRemoteExcludePaths exclusions: 100, then 200 checked, then stop. + if len(got.Files) != 0 || !got.MoreCandidates || got.CandidatesChecked != 300 || len(calls) != 3 || got.FileCount != 0 { + t.Fatalf("%d calls, %s", len(calls), raw) + } +} + +// A cancelled first page (deadline) also continues, and a complete later page +// clears the cancellation it carried. +func TestBoundaryFilterContinuesAfterCancelledPage(t *testing.T) { + target := Target{Repo: "org/repo", Commit: strings.Repeat("a", 40), RepositoryID: 7} + candidates := []string{"a.ts", "b.ts"} + var calls []string + c := pagedEngine(t, target, candidates, func(n string) string { + if n == "b.ts" { + return "x ft y" + } + return "left" + }, 1, 9000, &calls) + p := Pattern{Text: `\bft\b`} + q, _ := PatternQuery(p) + raw, err := c.SearchManyWithOptions(context.Background(), []Target{target}, q, DisplayOptions{Pattern: &p}) + if err != nil { + t.Fatal(err) + } + var got struct { + zoekt.SearchResult + MoreCandidates bool + } + json.Unmarshal(raw, &got) + if len(got.Files) != 1 || got.Files[0].FileName != "b.ts" || got.MoreCandidates || got.Stats.FilesSkippedDueToCancellation != 0 { + t.Fatalf("%s", raw) + } +} diff --git a/internal/zoektclient/local.go b/internal/zoektclient/local.go index 084d67d..a06c424 100644 --- a/internal/zoektclient/local.go +++ b/internal/zoektclient/local.go @@ -332,15 +332,34 @@ func (l *Local) searchExcluding(ctx context.Context, ids []uint32, q string, exc } aggregate := &zoekt.SearchResult{RepoURLs: map[string]string{}, LineFragments: map[string]string{}} matches := 0 + total, searched := 0, 0 + for _, v := range held { + total += len(v.searchers) + } + // Shards left unsearched because the time ran out count as ShardsSkipped, + // like the engine's own count, so the answer reports a deadline. +search: for _, v := range held { for _, s := range v.searchers { - if ctx.Err() != nil || (opts.TotalMaxMatchCount > 0 && matches >= opts.TotalMaxMatchCount) { - break + if err := ctx.Err(); err != nil { + if errors.Is(err, context.Canceled) { + return nil, err // the caller gave up: no partial answer + } + aggregate.Stats.ShardsSkipped += total - searched + break search + } + if opts.TotalMaxMatchCount > 0 && matches >= opts.TotalMaxMatchCount { + break search // the match budget is spent; MatchCount says so } + searched++ r, err := s.Search(ctx, parsed, opts) if err != nil { + if errors.Is(err, context.Canceled) { + return nil, err + } if errors.Is(err, context.DeadlineExceeded) { - break + aggregate.Stats.ShardsSkipped += total - searched + 1 + break search } return nil, fail("ENGINE_UNAVAILABLE", "Search engine request failed.", 503, true) } @@ -355,6 +374,11 @@ func (l *Local) searchExcluding(ctx context.Context, ids []uint32, q string, exc matches += r.Stats.MatchCount } } + // The engine notes a cancellation inside a shard only in its stats; a + // caller that gave up gets the cancellation, not a partial answer. + if errors.Is(ctx.Err(), context.Canceled) { + return nil, ctx.Err() + } aggregate.Files = index.SortAndTruncateFiles(aggregate.Files, opts) if aggregate.Files == nil { aggregate.Files = []zoekt.FileMatch{} diff --git a/internal/zoektclient/pattern.go b/internal/zoektclient/pattern.go index 99beb60..b7ff1a4 100644 --- a/internal/zoektclient/pattern.go +++ b/internal/zoektclient/pattern.go @@ -5,7 +5,6 @@ import ( "regexp/syntax" "slices" "strings" - "unicode" "unicode/utf8" "github.com/sourcegraph/zoekt/query" @@ -62,6 +61,7 @@ func PatternQuery(p Pattern) (string, error) { return "", fail("INVALID_PATTERN", "pattern must consume at least one character; zero-width-only or nullable searches are not supported.", 400, false) } } + serialized = keepRegexp(serialized) mode := "yes" q := "( case:" + mode + " content:" + quoteQ(serialized) + " ) " + skippedPlaceholder // Validate before broadening; invalid user globs must not become valid. @@ -88,19 +88,21 @@ func PatternQuery(p Pattern) (string, error) { return q, nil } -// lineRegexp removes every way to match a newline and rewrites inline (?i) -// literals into explicit classes: the pinned engine turns a fold-case literal -// into a case-sensitive substring of its upper-case runes. +// lineRegexp removes every way to match a newline. Fold-case literals stay +// literals: the engine looks them up in its trigram index case-insensitively +// and verifies each line with Go's (?i), which is rg's -i. Spelling them as +// classes ([Mm][Uu][Ssſ]…) cut a literal at every s and k (whose fold orbit +// also holds ſ U+017F and the Kelvin sign U+212A) and, below three runes, +// dropped it from the lookup: "must.?eat" scanned every file containing "eat". +// Known difference: the index lookup compares same-length case variants, so +// a line that spells s as ſ or k as the Kelvin sign is not found by indexed +// search (scanning without an index still finds it). func lineRegexp(re *syntax.Regexp) (*syntax.Regexp, error) { switch re.Op { case syntax.OpLiteral: if slices.Contains(re.Rune, '\n') { return nil, errMultiline } - if re.Flags&syntax.FoldCase != 0 { - re.Flags &^= syntax.FoldCase - return foldLiteral(re), nil - } case syntax.OpCharClass: re.Rune = withoutNewline(re.Rune) if len(re.Rune) == 0 { @@ -120,32 +122,23 @@ func lineRegexp(re *syntax.Regexp) (*syntax.Regexp, error) { return re, nil } -func foldLiteral(re *syntax.Regexp) *syntax.Regexp { - parts := make([]*syntax.Regexp, 0, len(re.Rune)) - for _, r := range re.Rune { - orbit := []rune{r} - for f := unicode.SimpleFold(r); f != r; f = unicode.SimpleFold(f) { - orbit = append(orbit, f) - } - if len(orbit) == 1 { - parts = append(parts, &syntax.Regexp{Op: syntax.OpLiteral, Flags: re.Flags, Rune: orbit}) - continue - } - slices.Sort(orbit) - class := []rune{} - for _, f := range orbit { - if n := len(class); n > 0 && class[n-1]+1 == f { - class[n-1] = f - } else { - class = append(class, f, f) - } - } - parts = append(parts, &syntax.Regexp{Op: syntax.OpCharClass, Rune: class}) +// engineFlags are the flags the pinned engine parses content regexps with. +const engineFlags = syntax.ClassNL | syntax.PerlX | syntax.UnicodeGroups + +// keepRegexp stops the engine from turning a whole-pattern fold-case literal +// into a substring: it would drop the fold and match only the upper-case +// spelling ("-i fuzzy" found FUZZY, not fuzzy). An empty group keeps it a +// regexp with the same matches and the same index lookup. +func keepRegexp(serialized string) string { + re, err := syntax.Parse(serialized, engineFlags) + if err != nil { + return serialized } - if len(parts) == 1 { - return parts[0] + re = query.OptimizeRegexp(re, engineFlags) + if re.Op == syntax.OpLiteral && re.Flags&syntax.FoldCase != 0 { + return serialized + "(?:)" } - return &syntax.Regexp{Op: syntax.OpConcat, Sub: parts} + return serialized } func withoutNewline(ranges []rune) []rune { diff --git a/internal/zoektclient/pattern_equivalence_test.go b/internal/zoektclient/pattern_equivalence_test.go index 40dd202..c346e6a 100644 --- a/internal/zoektclient/pattern_equivalence_test.go +++ b/internal/zoektclient/pattern_equivalence_test.go @@ -29,6 +29,8 @@ var equivalenceCorpus = map[string]string{ "extra/中文.ts": "marker 直播审核\n", "extra/case.txt": "fooBAR fooBar FOObar\nfoobar foo_bar foo-bar\naaaa ab ac abc abbc\n", "extra/crlf.txt": "marker\r\nlast marker", + // Case-insensitive whole words and literals split by s/k. + "extra/fold.txt": "fuzzy lower\nFUZZY upper\nFuzzy title\nMUST EAT\nmust-eat\nkelvin 5k\n", "src/server.go": `package server @@ -94,6 +96,10 @@ var equivalenceCases = []equivalenceCase{ {name: "lazy quantifier", p: Pattern{Text: `a+?b`}}, {name: "POSIX character class", p: Pattern{Text: `[[:alpha:]]+[[:digit:]]+`}}, {name: "hex character escape", p: Pattern{Text: `\x61bc`}}, + {name: "ignore case whole word", p: Pattern{Text: "fuzzy", IgnoreCase: true}, grepE: true}, + {name: "fixed ignore case whole word", p: Pattern{Text: "fuzzy", FixedStrings: true, IgnoreCase: true}, grepE: true}, + {name: "inline ignore case whole word", p: Pattern{Text: "(?i)FUZZY"}}, + {name: "ignore case across s", p: Pattern{Text: "must.?eat", IgnoreCase: true}}, {name: "inline scoped case disable", p: Pattern{Text: `(?i:foo)(?-i:BAR)`, IgnoreCase: true}}, {name: "nested case flags", p: Pattern{Text: `(?i:foo(?-i:Bar))`}}, {name: "line anchors and CRLF", p: Pattern{Text: `^marker\r?$`}}, diff --git a/internal/zoektclient/pattern_filter.go b/internal/zoektclient/pattern_filter.go index a52ce61..d06e02c 100644 --- a/internal/zoektclient/pattern_filter.go +++ b/internal/zoektclient/pattern_filter.go @@ -170,7 +170,8 @@ func (f *patternFilter) apply(ctx context.Context, raw json.RawMessage) (json.Ra } // Preserve candidate counters when the engine omitted results: downstream // must still disclose truncation even when all displayed candidates fail. - if result.FileCount <= len(result.Files) && result.MatchCount <= candidateLines { + // A MatchCount at the engine's budget says the engine stopped early; keep it. + if result.FileCount <= len(result.Files) && result.MatchCount <= candidateLines && result.MatchCount < engineMatchBudget { result.FileCount = len(files) result.MatchCount = keptLines } diff --git a/internal/zoektclient/pattern_test.go b/internal/zoektclient/pattern_test.go index 210cd61..fbe108b 100644 --- a/internal/zoektclient/pattern_test.go +++ b/internal/zoektclient/pattern_test.go @@ -101,3 +101,31 @@ func TestGlobValidation(t *testing.T) { } } } + +// Case-insensitive literals stay literals for the engine, so its trigram +// index narrows the candidates (before, "must.?eat" kept only "EAT" and +// "-i fuzzy" became a case-sensitive substring "FUZZY"). +func TestIgnoreCaseKeepsIndexedLiterals(t *testing.T) { + for _, c := range []struct { + p Pattern + want string + }{ + {Pattern{Text: "must.?eat", IgnoreCase: true}, "(?i:MUST)"}, + {Pattern{Text: "location.?auth|locationPermission", IgnoreCase: true}, "(?i:LOCATION)"}, + {Pattern{Text: "locationPermission", FixedStrings: true, IgnoreCase: true}, "(?i:LOCATIONPERMISSION)"}, + {Pattern{Text: "fuzzy", IgnoreCase: true}, "(?i:FUZZY)"}, + } { + wire, err := PatternQuery(c.p) + if err != nil { + t.Fatal(err) + } + q, err := query.Parse(wire) + if err != nil { + t.Fatal(err) + } + got := q.String() + if !strings.Contains(got, c.want) || strings.Contains(got, "[Ss") || strings.Contains(got, "content_substr:\"FUZZY\"") { + t.Fatalf("%+v: engine query %s, want literal %s", c.p, got, c.want) + } + } +} diff --git a/scripts/deployment/cli-readme.md b/scripts/deployment/cli-readme.md index 6b1d724..5da4f70 100644 --- a/scripts/deployment/cli-readme.md +++ b/scripts/deployment/cli-readme.md @@ -38,7 +38,7 @@ A token acts as its owner: it reads what you can read, manages repositories you | MCP | `mcp` prints a client configuration | | Connection | `doctor` checks DNS, each IPv4/IPv6 address, HTTPS and the sign-in, and says what to do | -`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours). +`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--contains TEXT] [--limit N] [--access]` shows service logs of all instances (default: warnings and errors, last 24 hours); `--access` reads the request log instead (one line per request with route, method, status and duration), and `--contains` keeps lines containing a text such as a request id. `sourcegraph read ` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`. diff --git a/scripts/deployment/skill.md b/scripts/deployment/skill.md index 9f9a7d7..4677fc7 100644 --- a/scripts/deployment/skill.md +++ b/scripts/deployment/skill.md @@ -68,7 +68,7 @@ All changes go through the site API with the caller's permissions, exactly as on - **Delete, managers:** CLI only (`sourcegraph repo delete|managers`). Deletion is permanent (registration, Git data and indexes) and asks for the repository name; `sourcegraph repo purge` retries a deletion that did not finish. Only delete when the user explicitly asks. - **Updates:** repositories are checked on their schedule (`sync_interval_minutes`). A paused repository (`updates_paused`) is resumed by a manager with `sourcegraph repo resume ` or MCP `repository_settings` `resume_updates`. With `manual_updates=true` nothing updates automatically; run `sourcegraph jobs sync` when the user wants fresh content. - **Query errors:** managers read their repository's recorded query failures with `sourcegraph repo errors [--limit N] [--after CURSOR]` and one in full with `sourcegraph repo errors `; site administrators see every repository with `sourcegraph admin query-errors [--repo R]`. Entries at level `warning` are requests for a repository that is not registered — a wrong or guessed name, not a service fault; they are left out of the error rate. Check the name with `sourcegraph repos` before reporting them. -- **Service logs (administrators):** `sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` (or MCP `site_admin` action `logs` with the same `hours`/`level`/`msg`/`limit`) summarizes and lists the service log lines of every instance (default: warnings and errors of the last 24 hours, at most 14 days). Failed tasks are `repository_task_completed` lines: `cause` is `repository` (access, credentials, the code host; level WARN) or `service` (level ERROR). +- **Service logs (administrators):** `sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` (or MCP `site_admin` action `logs` with the same `hours`/`level`/`msg`/`limit`) summarizes and lists the service log lines of every instance (default: warnings and errors of the last 24 hours, at most 14 days). `--access` (MCP `access: true`) reads the request log instead: one line per request with `route`, `method`, `status` and `duration_ms`; `--contains TEXT` (MCP `contains`) keeps lines with a given text such as a request id. Failed tasks are `repository_task_completed` lines: `cause` is `repository` (access, credentials, the code host; level WARN) or `service` (level ERROR). - **Personal settings:** tokens and code-host PATs (`personal_settings` or `sourcegraph tokens|credentials`). Token visibility: `sourcegraph tokens create [--tag T]... [--exclude-public]`, `sourcegraph tokens scope [--tag T]... | --all-tags [--exclude-public|--include-public]`; the website shows a live preview of the repositories a token reaches. A token with a scope cannot manage tokens (`TOKEN_SCOPE_LOCKED`); change scopes on the website or with an unscoped token. - **Tags:** `sourcegraph tags` lists tags with repository counts; `sourcegraph tags rename ` renames the tag on every repository that has it; tags are unique across the site (`TAG_EXISTS` when the new name is taken; never merged), the user must manage all those repositories unless a site administrator (`TAG_MANAGEMENT_DENIED`), and token scopes follow. Rename only when the user asks. - **Site administration (administrators):** `site_settings`/`site_admin` or `sourcegraph admin ...` for repository defaults, public access, user roles, site-wide credentials, query errors, cluster status and service logs. @@ -80,5 +80,6 @@ All changes go through the site API with the caller's permissions, exactly as on - A branch (or default-branch) search, read, list or plugin query that cannot be answered from the branch's newest head yet (still indexing, or not loaded on that instance) is answered from the branch's newest indexed head and says so (`ServedHead` in the query API, `served_head` in plugins and MCP JSON, a `ServedHead:` line in MCP text). Cite the served commit and mention it when the user needs the very latest code. `resolve` still returns the newest head (with `ready_head` when it is not indexed); diff never falls back; exact SHAs are never substituted. - `REVISION_NOT_SEARCHABLE` (search): the commit has no index and its files are not on the service. Search one of the commits the message lists, or the branch; do not retry the same commit. `SEARCH_BUSY` (search): scans are busy on that instance; retry once after Retry-After. - `INDEX_NOT_READY`, `SCOPE_NOT_READY`, `CONTENT_NOT_READY` (reads and other tools): the version is not prepared; prepare it if authorized, otherwise report it. To read, list or compare only, prepare its contents without an index (MCP `prepare` with `content_only: true`, or `sourcegraph jobs retry --kind content --commit SHA`), which is faster; search then scans its files. For indexed search use MCP `prepare` or `--kind index`. A reader who does not manage the repository may prepare contents only, of a full 40-character SHA (never a branch), when the site allows it (capabilities list `prepare-content-reader`): an already readable commit answers `stage: ready` with no job; `RATE_LIMITED` (`detail.scope` user or repository), `READER_PREPARE_FULL` and `REPOSITORY_STORAGE_BUSY` carry a retry time — wait for it once or report, do not loop. Without a token, MCP `prepare` answers `LOGIN_REQUIRED`: tell the user to sign in on the website, create a personal token and send it as `Authorization: Bearer `. +- `Partial: true` (search): the answer is incomplete; `PartialReasons` says why (`deadline`: the time limit stopped it before every candidate file was checked, results can differ between runs; `filter_candidates`: word-boundary or glob verification left candidates unchecked; `scan_stopped`: a hybrid answer's scan of changed files stopped early; `match_limit`; `engine_error`) and `Hint` what to do. Narrow with paths or globs, use a fixed string or a more specific term, or split alternatives; never read missing files as absent. - `SITE_FROZEN`: the site is read-only for maintenance; retry later. - `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection and a TLS handshake to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically, including when an address connects but never completes TLS, and remembers the family that worked. MCP clients keep the first address that connects: when doctor reports one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`); on Node 18 add `--network-family-autoselection`. Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output. diff --git a/skills/sourcegraph/SKILL.md b/skills/sourcegraph/SKILL.md index fef97e3..c10126a 100644 --- a/skills/sourcegraph/SKILL.md +++ b/skills/sourcegraph/SKILL.md @@ -68,7 +68,7 @@ All changes go through the site API with the caller's permissions, exactly as on - **Delete, managers:** CLI only (`sourcegraph repo delete|managers`). Deletion is permanent (registration, Git data and indexes) and asks for the repository name; `sourcegraph repo purge` retries a deletion that did not finish. Only delete when the user explicitly asks. - **Updates:** repositories are checked on their schedule (`sync_interval_minutes`). A paused repository (`updates_paused`) is resumed by a manager with `sourcegraph repo resume ` or MCP `repository_settings` `resume_updates`. With `manual_updates=true` nothing updates automatically; run `sourcegraph jobs sync` when the user wants fresh content. - **Query errors:** managers read their repository's recorded query failures with `sourcegraph repo errors [--limit N] [--after CURSOR]` and one in full with `sourcegraph repo errors `; site administrators see every repository with `sourcegraph admin query-errors [--repo R]`. Entries at level `warning` are requests for a repository that is not registered — a wrong or guessed name, not a service fault; they are left out of the error rate. Check the name with `sourcegraph repos` before reporting them. -- **Service logs (administrators):** `sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` (or MCP `site_admin` action `logs` with the same `hours`/`level`/`msg`/`limit`) summarizes and lists the service log lines of every instance (default: warnings and errors of the last 24 hours, at most 14 days). Failed tasks are `repository_task_completed` lines: `cause` is `repository` (access, credentials, the code host; level WARN) or `service` (level ERROR). +- **Service logs (administrators):** `sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` (or MCP `site_admin` action `logs` with the same `hours`/`level`/`msg`/`limit`) summarizes and lists the service log lines of every instance (default: warnings and errors of the last 24 hours, at most 14 days). `--access` (MCP `access: true`) reads the request log instead: one line per request with `route`, `method`, `status` and `duration_ms`; `--contains TEXT` (MCP `contains`) keeps lines with a given text such as a request id. Failed tasks are `repository_task_completed` lines: `cause` is `repository` (access, credentials, the code host; level WARN) or `service` (level ERROR). - **Personal settings:** tokens and code-host PATs (`personal_settings` or `sourcegraph tokens|credentials`). Token visibility: `sourcegraph tokens create [--tag T]... [--exclude-public]`, `sourcegraph tokens scope [--tag T]... | --all-tags [--exclude-public|--include-public]`; the website shows a live preview of the repositories a token reaches. A token with a scope cannot manage tokens (`TOKEN_SCOPE_LOCKED`); change scopes on the website or with an unscoped token. - **Tags:** `sourcegraph tags` lists tags with repository counts; `sourcegraph tags rename ` renames the tag on every repository that has it; tags are unique across the site (`TAG_EXISTS` when the new name is taken; never merged), the user must manage all those repositories unless a site administrator (`TAG_MANAGEMENT_DENIED`), and token scopes follow. Rename only when the user asks. - **Site administration (administrators):** `site_settings`/`site_admin` or `sourcegraph admin ...` for repository defaults, public access, user roles, site-wide credentials, query errors, cluster status and service logs. @@ -80,5 +80,6 @@ All changes go through the site API with the caller's permissions, exactly as on - A branch (or default-branch) search, read, list or plugin query that cannot be answered from the branch's newest head yet (still indexing, or not loaded on that instance) is answered from the branch's newest indexed head and says so (`ServedHead` in the query API, `served_head` in plugins and MCP JSON, a `ServedHead:` line in MCP text). Cite the served commit and mention it when the user needs the very latest code. `resolve` still returns the newest head (with `ready_head` when it is not indexed); diff never falls back; exact SHAs are never substituted. - `REVISION_NOT_SEARCHABLE` (search): the commit has no index and its files are not on the service. Search one of the commits the message lists, or the branch; do not retry the same commit. `SEARCH_BUSY` (search): scans are busy on that instance; retry once after Retry-After. - `INDEX_NOT_READY`, `SCOPE_NOT_READY`, `CONTENT_NOT_READY` (reads and other tools): the version is not prepared; prepare it if authorized, otherwise report it. To read, list or compare only, prepare its contents without an index (MCP `prepare` with `content_only: true`, or `sourcegraph jobs retry --kind content --commit SHA`), which is faster; search then scans its files. For indexed search use MCP `prepare` or `--kind index`. A reader who does not manage the repository may prepare contents only, of a full 40-character SHA (never a branch), when the site allows it (capabilities list `prepare-content-reader`): an already readable commit answers `stage: ready` with no job; `RATE_LIMITED` (`detail.scope` user or repository), `READER_PREPARE_FULL` and `REPOSITORY_STORAGE_BUSY` carry a retry time — wait for it once or report, do not loop. Without a token, MCP `prepare` answers `LOGIN_REQUIRED`: tell the user to sign in on the website, create a personal token and send it as `Authorization: Bearer `. +- `Partial: true` (search): the answer is incomplete; `PartialReasons` says why (`deadline`: the time limit stopped it before every candidate file was checked, results can differ between runs; `filter_candidates`: word-boundary or glob verification left candidates unchecked; `scan_stopped`: a hybrid answer's scan of changed files stopped early; `match_limit`; `engine_error`) and `Hint` what to do. Narrow with paths or globs, use a fixed string or a more specific term, or split alternatives; never read missing files as absent. - `SITE_FROZEN`: the site is read-only for maintenance; retry later. - `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection and a TLS handshake to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically, including when an address connects but never completes TLS, and remembers the family that worked. MCP clients keep the first address that connects: when doctor reports one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`); on Node 18 add `--network-family-autoselection`. Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output.