Search: order results newest first in every group

Chat hits sort by the chat's last use whatever field matched, and run,
step, field, artifact and pipeline hits sort by their own date, before
the result cap applies so the cap drops the oldest. Each kind's row scan
also walks newest first. Score still reports the match tier. The app
sorts both groups newest first as well.
This commit is contained in:
2026-11-03 13:35:27 +00:00
parent 63a67e0621
commit 6ca415c134
10 changed files with 293 additions and 76 deletions
+12 -39
View File
@@ -90,10 +90,10 @@ func (s *Store) Search(ctx context.Context, req protocol.SearchRequest, now time
for i := range results {
results[i].Score = 0
}
sortRecentSearchResults(results)
} else {
sortSearchResults(results)
}
// Hits are ordered newest first before the cap, so the cap drops the
// oldest; Score still records how each hit matched.
sortRecentSearchResults(results)
if len(results) > response.Cap {
results = results[:response.Cap]
response.Truncated = true
@@ -220,24 +220,9 @@ func searchContains(value, text string) bool {
return text != "" && strings.Contains(strings.ToLower(value), strings.ToLower(text))
}
func sortSearchResults(results []protocol.SearchResult) {
sort.SliceStable(results, func(i, j int) bool {
a, b := results[i], results[j]
if a.Score != b.Score {
return a.Score > b.Score
}
if a.Recency != b.Recency {
return a.Recency > b.Recency
}
if a.Kind != b.Kind {
return a.Kind < b.Kind
}
return a.Target < b.Target
})
}
// Browsing has no relevance score. Numeric entity IDs, then visit/version IDs,
// break equal timestamps deterministically (not lexical "run:9" vs "run:10").
// sortRecentSearchResults orders hits newest first by Recency, for a text
// search and a browse alike. 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 {
@@ -284,7 +269,7 @@ WHERE v.version=(SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=p.
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 ?`
query += ` AND lower(p.name) LIKE ? ESCAPE '\' ORDER BY v.created_at DESC,v.pipeline_id DESC LIMIT ?`
args = append(args, searchLike(terms.Text))
}
args = append(args, searchCandidateLimit(terms))
@@ -345,11 +330,7 @@ FROM pipeline_versions v`
args = append(args, n)
wanted, numeric = n, true
}
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 ?"
}
query += " ORDER BY v.created_at DESC,v.pipeline_id DESC,v.version DESC LIMIT ?"
args = append(args, searchCandidateLimit(terms))
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
@@ -407,11 +388,7 @@ 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)
}
if terms.Browse {
query += " ORDER BY r.created_at DESC,r.id DESC LIMIT ?"
} else {
query += " ORDER BY r.id DESC LIMIT ?"
}
query += " ORDER BY r.created_at DESC,r.id DESC LIMIT ?"
args = append(args, searchCandidateLimit(terms))
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
@@ -474,7 +451,7 @@ func searchSteps(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *searc
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 ?`
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.started_at DESC,s.run_id DESC,s.sequence DESC LIMIT ?`
pattern := searchLike(terms.Text)
args = append(args, pattern, pattern, pattern, pattern)
}
@@ -543,11 +520,7 @@ func searchFields(ctx context.Context, tx *sql.Tx, terms searchTerms, scan *sear
// 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.
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 ?"
}
query += " ORDER BY s.started_at DESC,s.run_id DESC,s.sequence DESC LIMIT ?"
rows, err := tx.QueryContext(ctx, query, protocol.SearchMaxScanSteps+1)
if err != nil {
return nil, err
@@ -622,7 +595,7 @@ FROM step_artifacts a JOIN pipeline_runs r ON r.id=a.run_id`
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 ?`
query += ` WHERE lower(a.artifacts_json) LIKE ? ESCAPE '\' ORDER BY r.created_at DESC,r.id DESC,a.sequence DESC LIMIT ?`
args = append(args, searchLike(terms.Text))
}
// Metadata rows can contain several artifacts or malformed retained JSON.
+71 -9
View File
@@ -205,16 +205,14 @@ func TestSearchRankingExactSubstringBodyAndRecency(t *testing.T) {
t.Fatal(err)
}
seen := map[int]bool{}
for i, hit := range response.Results {
for _, hit := range response.Results {
seen[hit.Score] = true
if i > 0 && response.Results[i-1].Score < hit.Score {
t.Fatalf("scores not descending: %+v", response.Results)
}
}
assertNewestFirst(t, response.Results)
if !seen[3] || !seen[2] || !seen[1] {
t.Fatalf("expected exact/substring/body tiers: %+v", response.Results)
}
// The exact pipeline match outranks the substring pipeline match.
// Scores still record how a pipeline name matched.
exactIndex, substringIndex := -1, -1
for i, hit := range response.Results {
if hit.Pipeline == nil {
@@ -233,11 +231,11 @@ func TestSearchRankingExactSubstringBodyAndRecency(t *testing.T) {
t.Fatalf("substring name scored %d", hit.Score)
}
}
if exactIndex < 0 || substringIndex < 0 || exactIndex > substringIndex {
t.Fatalf("exact name must outrank a name substring: %+v", response.Results)
if exactIndex < 0 || substringIndex < 0 {
t.Fatalf("both pipeline names must match: %+v", response.Results)
}
// Equal-tier ties break by recency.
// Hits order by recency whatever their tier.
older, _, err := store.CreateRun(ctx, definition, "alpha-older", "/work", false, nil, map[string]any{"prompt": "alpha"})
if err != nil {
t.Fatal(err)
@@ -265,7 +263,71 @@ func TestSearchRankingExactSubstringBodyAndRecency(t *testing.T) {
}
}
if olderIndex < 0 || newerIndex < 0 || newerIndex > olderIndex {
t.Fatalf("recency tie-break lost: older=%d newer=%d", olderIndex, newerIndex)
t.Fatalf("recency order lost: older=%d newer=%d", olderIndex, newerIndex)
}
assertNewestFirst(t, response.Results)
}
func assertNewestFirst(t *testing.T, results []protocol.SearchResult) {
t.Helper()
for i := 1; i < len(results); i++ {
if results[i-1].Recency < results[i].Recency {
t.Fatalf("results not newest first at %d: %+v", i, results)
}
}
}
// TestSearchOrdersByDateAndCapKeepsNewest: an exact pipeline-name match on an
// old pipeline sorts below a newer run's body match, and a cap keeps the
// newest hits rather than the best-scored ones.
func TestSearchOrdersByDateAndCapKeepsNewest(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "order.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "gamma", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, _ := store.Get(ctx, items[0].ID, 1)
if _, err := store.db.Exec("UPDATE pipeline_versions SET created_at='2020-01-01 00:00:00'"); err != nil {
t.Fatal(err)
}
var runs []int64
for i, created := range []string{"2026-03-01 00:00:00", "2026-01-01 00:00:00", "2026-02-01 00:00:00"} {
run, _, err := store.CreateRun(ctx, definition, "key-"+strconv.Itoa(i), "/work/gamma-"+strconv.Itoa(i), false, nil, nil)
if err != nil {
t.Fatal(err)
}
setCreated(t, store, run, created)
runs = append(runs, run)
}
response, err := store.Search(ctx, protocol.SearchRequest{Query: "gamma", Kind: protocol.SearchKindRun}, time.Now())
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 3 || response.Results[0].Run.ID != runs[0] || response.Results[1].Run.ID != runs[2] || response.Results[2].Run.ID != runs[1] {
t.Fatalf("runs = %+v, want created newest first", response.Results)
}
all, err := store.Search(ctx, protocol.SearchRequest{Query: "gamma"}, time.Now())
if err != nil {
t.Fatal(err)
}
assertNewestFirst(t, all.Results)
last := all.Results[len(all.Results)-1]
if last.Pipeline == nil || last.Score != 3 {
t.Fatalf("oldest hit = %+v, want the exact-name pipeline last despite its score", last)
}
capped, err := store.Search(ctx, protocol.SearchRequest{Query: "gamma", Limit: 2}, time.Now())
if err != nil {
t.Fatal(err)
}
if !capped.Truncated || len(capped.Results) != 2 || capped.Results[0].Run.ID != runs[0] || capped.Results[1].Run.ID != runs[2] {
t.Fatalf("capped = %+v, want the two newest runs", capped.Results)
}
}