search: browse bounded recent items with kind-only queries

This commit is contained in:
2026-10-20 17:54:00 +01:00
parent cce7ea903a
commit 9cdfd9d9ab
12 changed files with 477 additions and 94 deletions
+151 -39
View File
@@ -29,13 +29,17 @@ func (s *Store) Search(ctx context.Context, req protocol.SearchRequest, now time
Cap: searchLimit(req.Limit),
ScanBoundBytes: protocol.SearchMaxScanBytes,
}
// An empty query is a well-defined no-op, never a match-everything scan.
if strings.TrimSpace(req.Query) == "" {
// Empty text without a kind remains a no-op. A validated kind explicitly
// requests bounded recent canonical rows, never a wildcard text search.
browse := strings.TrimSpace(req.Query) == ""
if browse && kind == "" {
return response, nil
}
terms := parseSearchTerms(req.Query, now)
terms.Browse = browse
terms.Limit = response.Cap
// A bare status word or date selects runs; it is never treated as body text.
selectorOnly := terms.Text == ""
selectorOnly := terms.Text == "" && !browse
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
@@ -82,7 +86,14 @@ func (s *Store) Search(ctx context.Context, req protocol.SearchRequest, now time
response.Truncated = true
}
sortSearchResults(results)
if browse {
for i := range results {
results[i].Score = 0
}
sortRecentSearchResults(results)
} else {
sortSearchResults(results)
}
if len(results) > response.Cap {
results = results[:response.Cap]
response.Truncated = true
@@ -118,6 +129,8 @@ func searchLimit(limit int) int {
// searchTerms is the parsed query. Text carries free text; Status and the
// From/To window carry a bare status word or a date expression that selects runs.
type searchTerms struct {
Browse bool
Limit int
Text string
Status string
HasDate bool
@@ -174,6 +187,13 @@ const (
// scale without limit. Field text uses the separate SearchMaxScanSteps budget.
const searchRowBudget = 2000
func searchCandidateLimit(terms searchTerms) int {
if terms.Browse {
return searchLimit(terms.Limit) + 1
}
return searchRowBudget + 1
}
// searchLike builds a case-insensitive substring pattern, escaping LIKE
// metacharacters so a query can never broaden the pattern.
func searchLike(text string) string {
@@ -216,15 +236,59 @@ func sortSearchResults(results []protocol.SearchResult) {
})
}
// Browsing has no relevance score. Numeric entity IDs, then visit/version IDs,
// break equal timestamps deterministically (not lexical "run:9" vs "run:10").
func sortRecentSearchResults(results []protocol.SearchResult) {
identity := func(hit protocol.SearchResult) (int64, int) {
switch {
case hit.Pipeline != nil:
return hit.Pipeline.ID, hit.Pipeline.Version
case hit.Version != nil:
return hit.Version.PipelineID, hit.Version.Version
case hit.Run != nil:
return hit.Run.ID, 0
case hit.Step != nil:
return hit.Step.RunID, hit.Step.Sequence
case hit.Field != nil:
return hit.Field.RunID, hit.Field.Sequence
case hit.Artifact != nil:
return hit.Artifact.RunID, hit.Artifact.Sequence
}
return 0, 0
}
sort.SliceStable(results, func(i, j int) bool {
a, b := results[i], results[j]
if a.Recency != b.Recency {
return a.Recency > b.Recency
}
ai, as := identity(a)
bi, bs := identity(b)
if ai != bi {
return ai > bi
}
if as != bs {
return as > bs
}
return a.Target < b.Target
})
}
func searchPipelines(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *searchScan) ([]protocol.SearchResult, error) {
if terms.Text == "" {
if terms.Text == "" && !terms.Browse {
return nil, nil
}
rows, err := tx.QueryContext(ctx, `SELECT p.id,p.name,v.version,json_array_length(v.graph_json,'$.stages'),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',v.created_at),'')
query := `SELECT p.id,p.name,v.version,json_array_length(v.graph_json,'$.stages'),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',v.created_at),'')
FROM pipelines p JOIN pipeline_versions v ON v.pipeline_id=p.id
WHERE v.version=(SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=p.id)
AND lower(p.name) LIKE ? ESCAPE '\'
ORDER BY p.name,p.id LIMIT ?`, searchLike(terms.Text), searchRowBudget+1)
WHERE v.version=(SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=p.id)`
var args []any
if terms.Browse {
query += " ORDER BY v.created_at DESC,v.pipeline_id DESC,v.version DESC LIMIT ?"
} else {
query += ` AND lower(p.name) LIKE ? ESCAPE '\' ORDER BY p.name,p.id LIMIT ?`
args = append(args, searchLike(terms.Text))
}
args = append(args, searchCandidateLimit(terms))
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
@@ -244,6 +308,9 @@ ORDER BY p.name,p.id LIMIT ?`, searchLike(terms.Text), searchRowBudget+1)
return nil, err
}
score, ok := searchTier(name, terms.Text)
if terms.Browse {
score, ok = 0, true
}
if !ok {
continue
}
@@ -257,12 +324,20 @@ ORDER BY p.name,p.id LIMIT ?`, searchLike(terms.Text), searchRowBudget+1)
}
func searchVersions(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *searchScan) ([]protocol.SearchResult, error) {
if terms.Text == "" {
if terms.Text == "" && !terms.Browse {
return nil, nil
}
query := `SELECT v.pipeline_id,v.version,v.content_hash,COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',v.created_at),''),v.source
FROM pipeline_versions v WHERE lower(v.source) LIKE ? ESCAPE '\'`
args := []any{searchLike(terms.Text)}
source := "v.source"
if terms.Browse {
source = "''" // Browsing needs metadata only, never retained source text.
}
query := `SELECT v.pipeline_id,v.version,v.content_hash,COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',v.created_at),''),` + source + `
FROM pipeline_versions v`
var args []any
if !terms.Browse {
query += ` WHERE lower(v.source) LIKE ? ESCAPE '\'`
args = append(args, searchLike(terms.Text))
}
var wanted int64
numeric := false
if n, err := parsePositiveInt(terms.Text); err == nil {
@@ -270,8 +345,12 @@ FROM pipeline_versions v WHERE lower(v.source) LIKE ? ESCAPE '\'`
args = append(args, n)
wanted, numeric = n, true
}
query += " ORDER BY v.pipeline_id,v.version DESC LIMIT ?"
args = append(args, searchRowBudget+1)
if terms.Browse {
query += " ORDER BY v.created_at DESC,v.pipeline_id DESC,v.version DESC LIMIT ?"
} else {
query += " ORDER BY v.pipeline_id,v.version DESC LIMIT ?"
}
args = append(args, searchCandidateLimit(terms))
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
@@ -292,7 +371,9 @@ FROM pipeline_versions v WHERE lower(v.source) LIKE ? ESCAPE '\'`
return nil, err
}
score, matched := 1, "source"
if numeric && int64(version) == wanted {
if terms.Browse {
score, matched = 0, ""
} else if numeric && int64(version) == wanted {
score, matched = 3, "version"
} else if !searchContains(source, terms.Text) {
continue
@@ -313,6 +394,8 @@ func searchRuns(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *search
var query string
var args []any
switch {
case terms.Browse:
query = base
case terms.Status != "":
query = base + " WHERE r.status=?"
args = append(args, terms.Status)
@@ -324,8 +407,12 @@ func searchRuns(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *search
pattern := searchLike(terms.Text)
args = append(args, pattern, pattern, pattern, pattern, terms.Text)
}
query += " ORDER BY r.id DESC LIMIT ?"
args = append(args, searchRowBudget+1)
if terms.Browse {
query += " ORDER BY r.created_at DESC,r.id DESC LIMIT ?"
} else {
query += " ORDER BY r.id DESC LIMIT ?"
}
args = append(args, searchCandidateLimit(terms))
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
@@ -345,7 +432,9 @@ func searchRuns(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *search
return nil, err
}
score, matched := 1, "status"
if terms.Status != "" {
if terms.Browse {
score, matched = 0, ""
} else if terms.Status != "" {
matched = "status"
} else if terms.HasDate {
matched = "created_at"
@@ -377,14 +466,20 @@ func searchRuns(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *search
}
func searchSteps(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *searchScan) ([]protocol.SearchResult, error) {
if terms.Text == "" {
if terms.Text == "" && !terms.Browse {
return nil, nil
}
pattern := searchLike(terms.Text)
rows, err := tx.QueryContext(ctx, `SELECT s.run_id,s.sequence,s.stage_key,s.outcome,s.target,s.diagnostic,`+searchStepRecency+`,`+searchStepEvidence+`
`+searchStepJoin+`
WHERE lower(s.stage_key) LIKE ? ESCAPE '\' OR lower(s.outcome) LIKE ? ESCAPE '\' OR lower(s.target) LIKE ? ESCAPE '\' OR lower(s.diagnostic) LIKE ? ESCAPE '\'
ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?`, pattern, pattern, pattern, pattern, searchRowBudget+1)
query := `SELECT s.run_id,s.sequence,s.stage_key,s.outcome,s.target,s.diagnostic,` + searchStepRecency + `,` + searchStepEvidence + ` ` + searchStepJoin
var args []any
if terms.Browse {
query += " ORDER BY s.started_at DESC,s.run_id DESC,s.sequence DESC LIMIT ?"
} else {
query += ` WHERE lower(s.stage_key) LIKE ? ESCAPE '\' OR lower(s.outcome) LIKE ? ESCAPE '\' OR lower(s.target) LIKE ? ESCAPE '\' OR lower(s.diagnostic) LIKE ? ESCAPE '\' ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?`
pattern := searchLike(terms.Text)
args = append(args, pattern, pattern, pattern, pattern)
}
args = append(args, searchCandidateLimit(terms))
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
@@ -404,7 +499,9 @@ ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?`, pattern, pattern, pattern, patt
return nil, err
}
score, matched := 1, "diagnostic"
if s, ok := searchTier(stage, terms.Text); ok {
if terms.Browse {
score, matched = 0, ""
} else if s, ok := searchTier(stage, terms.Text); ok {
score, matched = s, "stage"
} else if searchContains(outcome, terms.Text) {
matched = "outcome"
@@ -440,14 +537,18 @@ type searchScan struct {
}
func searchFields(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *searchScan) ([]protocol.SearchResult, error) {
if terms.Text == "" {
if terms.Text == "" && !terms.Browse {
return nil, nil
}
// One extra step is requested so a scan that hits the step bound can see that
// more rows remain and report Truncated rather than ending silently.
rows, err := tx.QueryContext(ctx, `SELECT s.run_id,s.sequence,s.input_json,s.output_json,s.transcript,`+searchStepEvidence+`,`+searchStepRecency+`
`+searchStepJoin+`
ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?`, protocol.SearchMaxScanSteps+1)
query := `SELECT s.run_id,s.sequence,s.input_json,s.output_json,s.transcript,` + searchStepEvidence + `,` + searchStepRecency + ` ` + searchStepJoin
if terms.Browse {
query += " ORDER BY s.started_at DESC,s.run_id DESC,s.sequence DESC LIMIT ?"
} else {
query += " ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?"
}
rows, err := tx.QueryContext(ctx, query, protocol.SearchMaxScanSteps+1)
if err != nil {
return nil, err
}
@@ -498,7 +599,7 @@ ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?`, protocol.SearchMaxScanSteps+1)
Field: &protocol.SearchField{RunID: runID, Sequence: sequence, Field: field.name, Snippet: searchSnippet(text, terms.Text)},
})
}
if searchContains(transcript, terms.Text) {
if searchContains(transcript, terms.Text) || (terms.Browse && transcript != "") {
results = append(results, protocol.SearchResult{
Kind: protocol.SearchKindField, Target: searchFieldTarget(runID, sequence, "transcript"),
Score: 1, MatchedField: "transcript", Recency: recency,
@@ -510,14 +611,23 @@ ORDER BY s.run_id DESC,s.sequence DESC LIMIT ?`, protocol.SearchMaxScanSteps+1)
}
func searchArtifacts(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *searchScan) ([]protocol.SearchResult, error) {
if terms.Text == "" {
if terms.Text == "" && !terms.Browse {
return nil, nil
}
pattern := searchLike(terms.Text)
rows, err := tx.QueryContext(ctx, `SELECT a.run_id,a.sequence,a.artifacts_json,COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),'')
FROM step_artifacts a JOIN pipeline_runs r ON r.id=a.run_id
WHERE lower(a.artifacts_json) LIKE ? ESCAPE '\'
ORDER BY a.run_id DESC,a.sequence DESC LIMIT ?`, pattern, searchRowBudget+1)
query := `SELECT a.run_id,a.sequence,a.artifacts_json,COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),'')
FROM step_artifacts a JOIN pipeline_runs r ON r.id=a.run_id`
var args []any
if terms.Browse {
query = `SELECT a.run_id,a.sequence,a.artifacts_json,COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),'')
FROM pipeline_runs r CROSS JOIN step_artifacts a ON a.run_id=r.id
ORDER BY r.created_at DESC,r.id DESC,a.sequence DESC LIMIT ?`
} else {
query += ` WHERE lower(a.artifacts_json) LIKE ? ESCAPE '\' ORDER BY a.run_id DESC,a.sequence DESC LIMIT ?`
args = append(args, searchLike(terms.Text))
}
// Metadata rows can contain several artifacts or malformed retained JSON.
args = append(args, searchRowBudget+1)
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
@@ -544,7 +654,9 @@ ORDER BY a.run_id DESC,a.sequence DESC LIMIT ?`, pattern, searchRowBudget+1)
}
for _, file := range evidence.Files {
score, matched := 1, "content_type"
if s, ok := searchTier(file.Name, terms.Text); ok {
if terms.Browse {
score, matched = 0, ""
} else if s, ok := searchTier(file.Name, terms.Text); ok {
score, matched = s, "name"
} else if !searchContains(file.ContentType, terms.Text) {
continue
@@ -565,7 +677,7 @@ ORDER BY a.run_id DESC,a.sequence DESC LIMIT ?`, pattern, searchRowBudget+1)
func findMatch(value any, text string) (string, bool) {
switch typed := value.(type) {
case string:
if searchContains(typed, text) {
if searchContains(typed, text) || (text == "" && typed != "") {
return typed, true
}
case map[string]any: