-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_bench.go
More file actions
242 lines (223 loc) · 6.76 KB
/
Copy pathcommand_bench.go
File metadata and controls
242 lines (223 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package contexting
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
)
func newBenchCommand() *cobra.Command {
var rootPath string
var indexPath string
var casesPath string
var engines string
var opts SearchOptions
var jsonOut bool
var grepMaxBytes int
var byCategory bool
cmd := &cobra.Command{
Use: "bench",
Short: "Benchmark search engines against a query case set",
RunE: func(cmd *cobra.Command, args []string) error {
var absConfigPath string
if configPath != "" {
var cfgErr error
absConfigPath, cfgErr = filepath.Abs(configPath)
if cfgErr != nil {
return fmt.Errorf("resolve config path: %w", cfgErr)
}
}
cfg, err := LoadContextingConfig(absConfigPath)
if err != nil {
return err
}
if rootPath == "" {
if cfg.Bench.RootPath != "" {
rootPath = cfg.Bench.RootPath
} else {
rootPath, err = os.Getwd()
if err != nil {
return fmt.Errorf("get working directory: %w", err)
}
}
}
absRoot, err := filepath.Abs(rootPath)
if err != nil {
return fmt.Errorf("resolve root path: %w", err)
}
applyStringFlag(cmd, "index", &indexPath, cfg.Bench.IndexPath)
applyStringFlag(cmd, "cases", &casesPath, cfg.Bench.CasesPath)
applyIntFlag(cmd, "limit", &opts.Limit, cfg.Bench.Limit)
applyIntFlag(cmd, "min-score", &opts.MinScore, cfg.Bench.MinScore)
applyStringFlag(cmd, "engines", &engines, strings.Join(cfg.Bench.Engines, ","))
applyIntFlag(cmd, "grep-max-bytes", &grepMaxBytes, cfg.Bench.GrepMaxBytes)
if cfg.Bench.JSON != nil {
applyBoolFlag(cmd, "json", &jsonOut, *cfg.Bench.JSON)
}
if grepMaxBytes <= 0 {
grepMaxBytes = 1048576
}
if !cmd.Flags().Changed("index") {
indexPath = resolveConfigPath(absConfigPath, indexPath)
}
if !cmd.Flags().Changed("cases") {
casesPath = resolveConfigPath(absConfigPath, casesPath)
}
if casesPath == "" {
return fmt.Errorf("--cases is required")
}
cases, err := LoadCasesAuto(casesPath)
if err != nil {
return err
}
engineNames := strings.Split(engines, ",")
for i, name := range engineNames {
engineNames[i] = strings.TrimSpace(strings.ToLower(name))
}
for _, name := range engineNames {
if !isKnownEngine(name) {
return fmt.Errorf("unknown engine %q (known engines: %s)", name, strings.Join(knownEngines(), ", "))
}
}
engineList := instantiateEngines(engineNames)
var index *ContextIndex
needCtxt := false
for _, name := range engineNames {
if name == "ctxt" {
needCtxt = true
break
}
}
indexStart := time.Now()
index, err = LoadContextIndex(indexPath)
indexLoadMs := time.Since(indexStart).Milliseconds()
if err != nil {
if needCtxt {
return err
}
LogWarnf("index load failed, ctxt engine will be skipped: %v", err)
indexLoadMs = 0
index = &ContextIndex{RootPath: absRoot}
} else {
if index.RootPath == "" {
return fmt.Errorf("index missing root_path: regenerate index by running 'ctxt watch' or 'ctxt init' in the project directory")
}
if index.RootPath != absRoot {
return fmt.Errorf("index root path mismatch: expected %s, got %s. Use --root to specify the project directory or run from the project root", absRoot, index.RootPath)
}
}
if index == nil {
for i, name := range engineNames {
if name == "ctxt" {
engineNames = append(engineNames[:i], engineNames[i+1:]...)
break
}
}
engineList = instantiateEngines(engineNames)
index = &ContextIndex{RootPath: absRoot}
indexLoadMs = 0
}
out := runBench(BenchInput{
Index: index,
Cases: cases,
Engines: engineList,
Limit: opts.Limit,
MinScore: opts.MinScore,
GrepMaxBytes: grepMaxBytes,
})
out.IndexLoadMs = indexLoadMs
// Check if cases have categories
hasCategories := false
if len(cases) > 0 && cases[0].Category != "" {
hasCategories = true
}
if jsonOut {
if byCategory && hasCategories {
jsonStr, err := categoryReportToJSON(cases, out.Results, out.IndexLoadMs)
if err != nil {
return err
}
fmt.Println(jsonStr)
} else {
jsonStr, err := resultsToJSONBench(out)
if err != nil {
return err
}
fmt.Println(jsonStr)
}
return nil
}
if out.IndexLoadMs >= 0 {
fmt.Printf("Index load: %dms (one-time cost)\n", out.IndexLoadMs)
}
if needCtxt {
if index.Model != "" {
fmt.Printf("Index model: %s\n", index.Model)
} else {
fmt.Println("Note: No LLM synonyms in index (lexical only)")
}
fmt.Println()
}
if byCategory && hasCategories {
printCategoryReport(cases, out.Results)
} else {
printBenchSummary(out)
}
return nil
},
}
cmd.Flags().StringVar(&rootPath, "root", "", "Project root path (defaults to current working directory)")
cmd.Flags().StringVarP(&indexPath, "index", "i", ".ctxt/ctx_index.json", "Path to context JSON")
cmd.Flags().StringVarP(&casesPath, "cases", "c", "", "Path to eval cases JSON")
cmd.Flags().IntVarP(&opts.Limit, "limit", "n", 10, "Number of ranked search results per query")
cmd.Flags().IntVar(&opts.MinScore, "min-score", 1, "Minimum score required for candidate results")
cmd.Flags().StringVar(&engines, "engines", "ctxt,find,grep", "Engines to benchmark: ctxt,find,fd,grep,rg,hybrid,combined")
cmd.Flags().IntVar(&grepMaxBytes, "grep-max-bytes", 1048576, "Max file size in bytes for grep/rg engines")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Print full benchmark report as JSON")
cmd.Flags().BoolVar(&byCategory, "by-category", true, "Group report by category (for v2 case files)")
return cmd
}
// BenchInput is the testable input to runBench.
type BenchInput struct {
Index *ContextIndex
Cases []EvalCase
Engines []SearchEngine
Limit int
MinScore int
GrepMaxBytes int
}
// runBench executes every engine on every case and returns the full report.
func runBench(in BenchInput) BenchOutput {
out := BenchOutput{
Cases: in.Cases,
Results: make([][]EngineResult, 0, len(in.Cases)),
}
if len(in.Cases) == 0 {
return out
}
searchOpts := SearchOptions{
Limit: in.Limit,
MinScore: in.MinScore,
}
if searchOpts.Limit <= 0 {
searchOpts.Limit = 10
}
if searchOpts.MinScore < 0 {
searchOpts.MinScore = 1
}
if searchOpts.TypeFilter == "" {
searchOpts.TypeFilter = "all"
}
for _, c := range in.Cases {
perEngine := make([]EngineResult, 0, len(in.Engines))
for _, engine := range in.Engines {
res := engine.Search(c.Query, c.ExpectAny, in.Index, searchOpts, in.GrepMaxBytes)
perEngine = append(perEngine, res)
}
out.Results = append(out.Results, perEngine)
}
out.Summary = computeEngineSummaries(in.Cases, out.Results)
out.Misses = computeBenchMisses(in.Cases, out.Results)
return out
}