chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+195
View File
@@ -0,0 +1,195 @@
package reranking
import (
"context"
"encoding/json"
"sort"
"sync"
"unicode/utf8"
"academy/internal/logger"
"academy/internal/models/imageprep"
"academy/internal/models/rerank"
"academy/internal/types"
"golang.org/x/sync/errgroup"
)
// An image found by its own vector is judged by what it shows. A reranker
// that reads images is sent the image. A text reranker only sees the caption
// and OCR text, which speak for the image when the image is mostly text, but
// not when it is a photo, chart or diagram the caption can only summarize:
// there its rejection means "the caption does not say", not "irrelevant".
const (
// pictorialOCRRunes is the OCR length below which an image counts as
// pictorial: its words are labels, not its content. Empirical.
pictorialOCRRunes = 200
// maxKeptImages caps the pictorial image hits kept over a text
// reranker's rejection, so an image-heavy knowledge base cannot fill a
// context with images the vector merely brushed.
maxKeptImages = 2
// imageLoadConcurrency bounds image reads from storage.
imageLoadConcurrency = 4
// MinImageKeepScore is the least vector similarity that keeps a pictorial
// image hit over a text reranker. It sits above the 0.2 image recall
// threshold: recall only lets an image compete, keeping it needs more.
// Empirical, on the cosine scale most engines report.
MinImageKeepScore = 0.25
)
// ImageKeepScoreFor is Options.ImageKeepScore for a search whose text hits
// needed vectorThreshold: an image is kept over a text reranker only when its
// vector was at least as close as a text hit had to be, and never below
// MinImageKeepScore.
func ImageKeepScoreFor(vectorThreshold float64) float64 {
return max(vectorThreshold, MinImageKeepScore)
}
func isImageVectorHit(r *types.SearchResult) bool {
return r != nil && r.ChunkType == string(types.ChunkTypeImageVector)
}
// isPictorial reports whether an image hit's text falls short of its content:
// its images carry less OCR text than pictorialOCRRunes.
func isPictorial(ctx context.Context, r *types.SearchResult) bool {
var infos []types.ImageInfo
if err := json.Unmarshal([]byte(r.ImageInfo), &infos); err != nil || len(infos) == 0 {
logger.Warnf(ctx, "[Rerank] Unreadable image info on image hit %s; treating it as text", r.ID)
return false
}
runes := 0
for _, info := range infos {
runes += utf8.RuneCountInString(info.OCRText)
}
return runes < pictorialOCRRunes
}
// imageCandidates prepares the images of the image hits among candidates for
// a reranker that reads images. It returns the candidate positions scored as
// images and their images, in matching order; a hit whose image cannot be
// read or made to fit stays a text candidate.
func imageCandidates(
ctx context.Context, model rerank.Reranker, candidates []*types.SearchResult, opts Options,
) (positions []int, images []rerank.Image) {
imageModel, ok := rerank.AsImageReranker(model)
if !ok || opts.LoadImage == nil {
return nil, nil
}
limits := imageModel.ImageLimits()
prepared := make([]*rerank.Image, len(candidates))
var mu sync.Mutex
group, groupCtx := errgroup.WithContext(ctx)
group.SetLimit(imageLoadConcurrency)
for i, r := range candidates {
if !isImageVectorHit(r) {
continue
}
group.Go(func() error {
data, err := opts.LoadImage(groupCtx, r)
if err != nil {
logger.Warnf(groupCtx, "[Rerank] Image of %s unreadable, scoring its text: %v", r.ID, err)
return nil
}
img, err := imageprep.Prepare(data, limits)
if err != nil {
logger.Warnf(groupCtx, "[Rerank] Image of %s does not fit the model, scoring its text: %v", r.ID, err)
return nil
}
mu.Lock()
prepared[i] = &img
mu.Unlock()
return nil
})
}
_ = group.Wait()
for i, img := range prepared {
if img != nil {
positions = append(positions, i)
images = append(images, *img)
}
}
return positions, images
}
// scoreCandidates scores every candidate: the ones at imagePositions by their
// image, the rest by their passage. Indices of the returned scores refer to
// candidates. If the images cannot be scored they are scored as text, so an
// image call failing costs the images their advantage, not the whole rerank.
func scoreCandidates(
ctx context.Context, model rerank.Reranker, query string, passages []string,
imagePositions []int, images []rerank.Image,
) (scores []rerank.RankResult, scoredAsImage map[int]bool, err error) {
scoredAsImage = make(map[int]bool, len(imagePositions))
if len(images) > 0 {
imageModel, _ := rerank.AsImageReranker(model)
imageScores, imgErr := imageModel.RerankImages(ctx, query, images)
if imgErr != nil {
logger.Warnf(ctx, "[Rerank] Image scoring failed, scoring those hits as text: %v", imgErr)
} else {
for _, s := range imageScores {
if s.Index < 0 || s.Index >= len(imagePositions) {
continue
}
s.Index = imagePositions[s.Index]
scoredAsImage[s.Index] = true
scores = append(scores, s)
}
}
}
textPositions := make([]int, 0, len(passages))
textPassages := make([]string, 0, len(passages))
for i, p := range passages {
if !scoredAsImage[i] {
textPositions = append(textPositions, i)
textPassages = append(textPassages, p)
}
}
if len(textPassages) == 0 {
return scores, scoredAsImage, nil
}
textScores, err := model.Rerank(ctx, query, textPassages)
if err != nil {
return nil, nil, err
}
for _, s := range textScores {
if s.Index < 0 || s.Index >= len(textPositions) {
continue
}
s.Index = textPositions[s.Index]
scores = append(scores, s)
}
sort.SliceStable(scores, func(i, j int) bool { return scores[i].RelevanceScore > scores[j].RelevanceScore })
return scores, scoredAsImage, nil
}
// keptImages picks the pictorial image hits a text reranker rejected that
// their vector still vouches for: VectorScore at least opts.ImageKeepScore,
// strongest first, at most maxKeptImages. Hits scored by their image already
// had a fair judgement and are never kept over it.
func keptImages(
ctx context.Context, candidates []*types.SearchResult, scores, passing []rerank.RankResult,
scoredAsImage map[int]bool, opts Options,
) []rerank.RankResult {
if opts.ImageKeepScore <= 0 {
return nil
}
passed := make(map[int]bool, len(passing))
for _, p := range passing {
passed[p.Index] = true
}
var kept []rerank.RankResult
for _, s := range scores {
r := candidates[s.Index]
if passed[s.Index] || scoredAsImage[s.Index] || !isImageVectorHit(r) ||
r.VectorScore < opts.ImageKeepScore || !isPictorial(ctx, r) {
continue
}
kept = append(kept, s)
}
sort.SliceStable(kept, func(i, j int) bool {
return candidates[kept[i].Index].VectorScore > candidates[kept[j].Index].VectorScore
})
if len(kept) > maxKeptImages {
kept = kept[:maxKeptImages]
}
return kept
}
+195
View File
@@ -0,0 +1,195 @@
package reranking
import (
"bytes"
"context"
"encoding/json"
"errors"
"image"
"image/png"
"strings"
"testing"
"academy/internal/models/imageprep"
"academy/internal/models/rerank"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// textScorer scores a passage by a table keyed on its text, 0 when absent.
type textScorer struct {
scores map[string]float64
documents []string
err error
}
func (s *textScorer) Rerank(_ context.Context, _ string, documents []string) ([]rerank.RankResult, error) {
s.documents = append(s.documents, documents...)
if s.err != nil {
return nil, s.err
}
out := make([]rerank.RankResult, len(documents))
for i, d := range documents {
out[i] = rerank.RankResult{Index: i, RelevanceScore: s.scores[d]}
}
return out, nil
}
func (s *textScorer) GetModelName() string { return "text-rerank" }
func (s *textScorer) GetModelID() string { return "text-rerank-id" }
// visionScorer also reads images, scoring every image imageScore.
type visionScorer struct {
textScorer
imageScore float64
imageErr error
images int
}
func (s *visionScorer) AcceptsImages() bool { return true }
func (s *visionScorer) ImageLimits() imageprep.Limits { return imageprep.Limits{} }
func (s *visionScorer) RerankImages(_ context.Context, _ string, images []rerank.Image) (
[]rerank.RankResult, error,
) {
if s.imageErr != nil {
return nil, s.imageErr
}
s.images += len(images)
out := make([]rerank.RankResult, len(images))
for i := range images {
out[i] = rerank.RankResult{Index: i, RelevanceScore: s.imageScore}
}
return out, nil
}
func pngBytes(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
require.NoError(t, png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 4, 4))))
return buf.Bytes()
}
// imageHit is an image_vector hit whose caption is caption and whose image
// carries ocrRunes characters of OCR text.
func imageHit(id, caption string, vectorScore float64, ocrRunes int) *types.SearchResult {
info, _ := json.Marshal([]types.ImageInfo{{
URL: "resource://" + id, Caption: caption, OCRText: strings.Repeat("字", ocrRunes),
}})
return &types.SearchResult{
ID: id, Content: caption, ChunkType: string(types.ChunkTypeImageVector),
ImageInfo: string(info), Score: 0.4, VectorScore: vectorScore,
}
}
func textHit(id, content string) *types.SearchResult {
return &types.SearchResult{ID: id, Content: content, ChunkType: string(types.ChunkTypeText), Score: 0.6}
}
func TestRerankScoresImageHitsByTheirImageWhenTheModelReadsImages(t *testing.T) {
model := &visionScorer{
textScorer: textScorer{scores: map[string]float64{"refund policy text": 0.8}},
imageScore: 0.9,
}
in := []*types.SearchResult{
textHit("t1", "refund policy text"),
imageHit("img", "a red circle", 0.2, 0),
}
var loaded []string
res := Rerank(context.Background(), model, "q", in, Options{
Threshold: 0.5,
LoadImage: func(_ context.Context, r *types.SearchResult) ([]byte, error) {
loaded = append(loaded, r.ID)
return pngBytes(t), nil
},
})
assert.Equal(t, []string{"img"}, loaded)
assert.Equal(t, 1, model.images)
assert.NotContains(t, model.documents, "a red circle", "an image scored by its image is not also sent as text")
assert.Equal(t, "img,t1", ids(res.Results), "the caption says nothing; the image decides")
assert.Equal(t, 1, res.Diagnostics.ImagesScored)
}
func TestRerankFallsBackToTextWhenTheImageCannotBeScored(t *testing.T) {
cases := map[string]struct {
load func(context.Context, *types.SearchResult) ([]byte, error)
imageErr error
}{
"unreadable image": {load: func(context.Context, *types.SearchResult) ([]byte, error) {
return nil, errors.New("gone")
}},
"not an image": {load: func(context.Context, *types.SearchResult) ([]byte, error) {
return []byte("%PDF-1.7"), nil
}},
"image call fails": {load: func(context.Context, *types.SearchResult) ([]byte, error) {
return []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, nil
}, imageErr: errors.New("upstream 500")},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
model := &visionScorer{
textScorer: textScorer{scores: map[string]float64{"a red circle": 0.7}},
imageScore: 0.1, imageErr: tc.imageErr,
}
if tc.imageErr != nil {
tc.load = func(context.Context, *types.SearchResult) ([]byte, error) { return pngBytes(t), nil }
}
res := Rerank(context.Background(), model, "q",
[]*types.SearchResult{imageHit("img", "a red circle", 0.2, 0)},
Options{Threshold: 0.5, LoadImage: tc.load})
assert.Contains(t, model.documents, "a red circle", "scored by its text instead")
assert.Equal(t, "img", ids(res.Results))
assert.Zero(t, res.Diagnostics.ImagesScored)
})
}
}
func TestRerankKeepsPictorialImagesATextRerankerRejects(t *testing.T) {
model := &textScorer{scores: map[string]float64{"refund policy text": 0.8}}
in := []*types.SearchResult{
textHit("t1", "refund policy text"),
imageHit("photo-weak", "a photo", 0.30, 0),
imageHit("photo-strong", "another photo", 0.55, 10),
imageHit("photo-mid", "a third photo", 0.45, 0),
imageHit("photo-below", "a fourth photo", 0.10, 0),
// Mostly text: its OCR stands for it, so the text verdict stands.
imageHit("screenshot", "a screenshot", 0.90, pictorialOCRRunes),
}
res := Rerank(context.Background(), model, "q", in, Options{Threshold: 0.5, ImageKeepScore: 0.2})
assert.Equal(t, "t1,photo-strong,photo-mid", ids(res.Results),
"ranked results first, then at most two pictorial images, strongest vector first")
for _, r := range res.Results[1:] {
assert.Equal(t, types.KeptByImageVector, r.Metadata[types.MetadataKeptBy])
}
assert.Empty(t, res.Results[0].Metadata[types.MetadataKeptBy])
assert.Equal(t, 2, res.Diagnostics.ImagesKept)
assert.Equal(t, 3, len(res.Indices))
assert.Equal(t, 2, res.Indices[1], "indices still point into the input")
}
func TestRerankKeepsAnImageEvenWhenNoTextPasses(t *testing.T) {
model := &textScorer{scores: map[string]float64{}}
res := Rerank(context.Background(), model, "q", []*types.SearchResult{
textHit("t1", "unrelated"),
imageHit("photo", "a photo", 0.6, 0),
}, Options{Threshold: 0.5, FallbackMinScore: DefaultFallbackMinScore, ImageKeepScore: 0.3})
assert.Equal(t, "photo", ids(res.Results))
assert.Equal(t, types.RerankOutcomeAllBelowThreshold, res.Diagnostics.Outcome)
}
func TestRerankKeepsNoImagesUnlessAsked(t *testing.T) {
model := &textScorer{scores: map[string]float64{"refund policy text": 0.8}}
in := []*types.SearchResult{textHit("t1", "refund policy text"), imageHit("photo", "a photo", 0.9, 0)}
res := Rerank(context.Background(), model, "q", in, Options{Threshold: 0.5})
assert.Equal(t, "t1", ids(res.Results))
// A model that read the image already judged it; its verdict stands.
vision := &visionScorer{textScorer: *model, imageScore: 0.1}
res = Rerank(context.Background(), vision, "q", in, Options{
Threshold: 0.5, ImageKeepScore: 0.2,
LoadImage: func(context.Context, *types.SearchResult) ([]byte, error) { return pngBytes(t), nil },
})
assert.Equal(t, "t1", ids(res.Results))
assert.Zero(t, res.Diagnostics.ImagesKept)
}
+124
View File
@@ -0,0 +1,124 @@
package reranking
import (
"context"
"math"
"academy/internal/searchutil"
"academy/internal/types"
)
// DefaultMMRLambda weighs relevance against redundancy in SelectMMR.
const DefaultMMRLambda = 0.7
// SelectMMR picks up to k results by Maximal Marginal Relevance over their
// Score and the token overlap of their enriched passages, and returns the
// indices of the picks in selection order. Ties go to the earlier result.
func SelectMMR(ctx context.Context, results []*types.SearchResult, k int, lambda float64) []int {
if k <= 0 || len(results) == 0 {
return nil
}
// The first pick has no redundancy term. Avoid passage cleaning and
// tokenization when the caller only wants that pick.
if k == 1 {
best, bestScore := 0, math.Inf(-1)
for i, r := range results {
if score := lambda*r.Score - (1.0-lambda)*0; score > bestScore {
best, bestScore = i, score
}
}
return []int{best}
}
remaining := make([]int, len(results))
for i := range results {
remaining[i] = i
}
tokens, offsets, postings := buildMMRPostings(ctx, results)
// Cache each candidate's maximum Jaccard against the selected passages.
// Postings count intersections only for candidates sharing a token with
// the new pick; disjoint passages have zero redundancy and need no update.
maxRedundancy := make([]float64, len(results))
intersections := make([]int, len(results))
taken := make([]bool, len(results))
touched := make([]int, 0, len(results))
selected := make([]int, 0, min(k, len(results)))
for len(selected) < k && len(remaining) > 0 {
bestPos := 0
bestScore := math.Inf(-1)
for pos, i := range remaining {
mmr := lambda*results[i].Score - (1.0-lambda)*maxRedundancy[i]
if mmr > bestScore {
bestScore = mmr
bestPos = pos
}
}
chosen := remaining[bestPos]
selected = append(selected, chosen)
taken[chosen] = true
remaining = append(remaining[:bestPos], remaining[bestPos+1:]...)
if len(selected) == k || len(remaining) == 0 {
break
}
touched = touched[:0]
for _, token := range tokens[chosen] {
for _, i := range postings[offsets[token]:offsets[token+1]] {
if taken[i] {
continue
}
if intersections[i] == 0 {
touched = append(touched, i)
}
intersections[i]++
}
}
for _, i := range touched {
intersection := intersections[i]
union := len(tokens[i]) + len(tokens[chosen]) - intersection
maxRedundancy[i] = math.Max(maxRedundancy[i], float64(intersection)/float64(union))
intersections[i] = 0
}
}
return selected
}
// buildMMRPostings interns each unique token and stores its candidate IDs in
// one flat array. offsets[t]:offsets[t+1] is token t's posting list. Each row
// comes from a token set, so one shared token contributes exactly once to a
// pair's intersection, regardless of its frequency in either passage.
func buildMMRPostings(
ctx context.Context, results []*types.SearchResult,
) (tokens [][]int, offsets, postings []int) {
termIDs := make(map[string]int)
var counts []int
tokens = make([][]int, len(results))
for i, r := range results {
set := searchutil.TokenizeSimple(EnrichedPassage(ctx, r))
tokens[i] = make([]int, 0, len(set))
for term := range set {
id, exists := termIDs[term]
if !exists {
id = len(counts)
termIDs[term] = id
counts = append(counts, 0)
}
counts[id]++
tokens[i] = append(tokens[i], id)
}
}
offsets = make([]int, len(counts)+1)
for id, count := range counts {
offsets[id+1] = offsets[id] + count
}
postings = make([]int, offsets[len(counts)])
// Reuse counts as insertion cursors; offsets stay unchanged for lookups.
copy(counts, offsets)
for i, row := range tokens {
for _, id := range row {
postings[counts[id]] = i
counts[id]++
}
}
return tokens, offsets, postings
}
+211
View File
@@ -0,0 +1,211 @@
package reranking
import (
"context"
"fmt"
"math"
"slices"
"strings"
"testing"
"academy/internal/searchutil"
"academy/internal/types"
)
// selectMMRNaive recomputes the redundancy of every candidate against every
// already-selected result on each round. It is the reference oracle for the
// incremental SelectMMR.
func selectMMRNaive(ctx context.Context, results []*types.SearchResult, k int, lambda float64) []int {
if k <= 0 || len(results) == 0 {
return nil
}
var selected []int
taken := make(map[int]bool)
for len(selected) < k && len(selected) < len(results) {
best, bestScore := -1, math.Inf(-1)
for i, r := range results {
if taken[i] {
continue
}
redundancy := 0.0
for _, s := range selected {
redundancy = math.Max(redundancy, searchutil.Jaccard(
searchutil.TokenizeSimple(EnrichedPassage(ctx, r)),
searchutil.TokenizeSimple(EnrichedPassage(ctx, results[s])),
))
}
if mmr := lambda*r.Score - (1.0-lambda)*redundancy; mmr > bestScore {
best, bestScore = i, mmr
}
}
selected = append(selected, best)
taken[best] = true
}
return selected
}
// mmrTestCorpus builds a deterministic candidate set whose passages share
// vocabulary in overlapping bands, so redundancy actually drives selection
// instead of the score alone.
func mmrTestCorpus(n int) []*types.SearchResult {
vocab := []string{
"insurance", "policy", "claim", "premium", "deductible", "liability",
"coverage", "endorsement", "underwriting", "reinsurance", "subrogation",
"indemnity", "exclusion", "rider", "annuity",
}
// Simple LCG so the corpus is identical on every run and every platform.
state := uint64(42)
next := func(mod int) int {
state = state*6364136223846793005 + 1442695040888963407
return int((state >> 33) % uint64(mod))
}
results := make([]*types.SearchResult, 0, n)
for i := 0; i < n; i++ {
words := make([]byte, 0, 128)
for j := 0; j < 12; j++ {
words = append(words, vocab[next(len(vocab))]...)
words = append(words, ' ')
}
results = append(results, &types.SearchResult{
ID: fmt.Sprintf("chunk-%03d", i),
Content: fmt.Sprintf("chunk %d %s", i, string(words)),
// Scores intentionally collide so tie-breaking is exercised too.
Score: float64(next(20)) / 20.0,
})
}
return results
}
func TestSelectMMR_matchesNaiveSelection(t *testing.T) {
t.Parallel()
ctx := context.Background()
results := mmrTestCorpus(40)
for _, tc := range []struct {
k int
lambda float64
}{
{k: 1, lambda: 0.7},
{k: 5, lambda: 0.7},
{k: 12, lambda: 0.3},
{k: 40, lambda: 0.9},
{k: 60, lambda: 0.5}, // k larger than the candidate count
} {
t.Run(fmt.Sprintf("k=%d/lambda=%.1f", tc.k, tc.lambda), func(t *testing.T) {
want := selectMMRNaive(ctx, results, tc.k, tc.lambda)
got := SelectMMR(ctx, results, tc.k, tc.lambda)
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("SelectMMR = %v, naive = %v", got, want)
}
})
}
}
func TestSelectMMR_emptyAndNonPositiveK(t *testing.T) {
t.Parallel()
ctx := context.Background()
if got := SelectMMR(ctx, mmrTestCorpus(3), 0, DefaultMMRLambda); got != nil {
t.Fatalf("expected nil for k=0, got %v", got)
}
if got := SelectMMR(ctx, nil, 5, DefaultMMRLambda); got != nil {
t.Fatalf("expected nil for empty candidates, got %v", got)
}
}
func BenchmarkSelectMMR(b *testing.B) {
ctx := context.Background()
results := mmrTestCorpus(250)
for i := 0; i < b.N; i++ {
SelectMMR(ctx, results, 250, DefaultMMRLambda)
}
}
func TestSelectMMR_preservesDiversityAndTies(t *testing.T) {
results := []*types.SearchResult{
{Content: "hybrid retrieval combines semantic vectors and keyword search", Score: 0.9},
{Content: "**hybrid retrieval** combines semantic vectors and keyword search", Score: 0.88},
{Content: "wiki construction extracts entities concepts and source citations", Score: 0.83},
}
if got := SelectMMR(context.Background(), results, 3, DefaultMMRLambda); !slices.Equal(got, []int{0, 2, 1}) {
t.Fatalf("selection = %v, want relevant, diverse, then redundant", got)
}
for _, r := range results {
r.Content, r.Score = "", 0.5
}
if got := SelectMMR(context.Background(), results, 10, DefaultMMRLambda); !slices.Equal(got, []int{0, 1, 2}) {
t.Fatalf("empty tied passages = %v, want original order", got)
}
}
func TestSelectMMR_multilingualEnrichedPassages(t *testing.T) {
results := []*types.SearchResult{
{Content: "混合检索结合语义向量和关键词索引,提高知识库检索覆盖率。", Score: 0.9},
{Content: "混合检索结合语义向量和关键词索引,提高知识库检索覆盖率。", Score: 0.85},
{Content: "Wiki 构建从文档抽取实体和概念,保留事实引用与来源分块。", Score: 0.8},
{Content: "retrieval", ImageInfo: `[{"caption":"semantic vectors and keyword search"}]`, Score: 0.75},
{
Content: "sources", Score: 0.7,
ChunkMetadata: types.JSON(`{"generated_questions":[
{"id":"q1","question":"How does wiki construction preserve source citations?"}
]}`),
},
{Content: "", Score: 0.7},
}
for _, lambda := range []float64{0, 0.3, DefaultMMRLambda, 1} {
for _, k := range []int{1, 3, len(results), len(results) + 1} {
got := SelectMMR(context.Background(), results, k, lambda)
want := selectMMRNaive(context.Background(), results, k, lambda)
if !slices.Equal(got, want) {
t.Fatalf("k=%d lambda=%v: selection = %v, naive = %v", k, lambda, got, want)
}
}
}
}
// mmrPassageCorpus models a rerank pool with overlapping vocabulary across
// documents and less overlap across topics. It is synthetic and deterministic;
// the benchmarks measure MMR computation, not end-to-end retrieval quality.
func mmrPassageCorpus(n, words int, chinese bool) []*types.SearchResult {
results := make([]*types.SearchResult, n)
terms := []string{"检索", "知识库", "向量", "索引", "语义", "文档", "引用", "实体", "概念", "构建", "答案", "模型"}
for i := range results {
var content strings.Builder
for j := 0; j < words; j++ {
if chinese {
fmt.Fprintf(&content, "%s ", terms[(i+j)%len(terms)])
}
// Different topics have disjoint bands; nearby documents within
// a topic share most of their vocabulary.
fmt.Fprintf(&content, "term%d ", (i%8)*1000+(j+i/8*7)%500)
}
results[i] = &types.SearchResult{
ID: fmt.Sprintf("chunk-%03d", i), Content: content.String(),
Score: 1 - float64(i%100)/200,
}
}
return results
}
func BenchmarkSelectMMRPassages(b *testing.B) {
ctx := context.Background()
for _, tc := range []struct {
name string
n, words, k int
chinese bool
}{
{name: "short", n: 50, words: 12, k: 10},
{name: "english_top10", n: 200, words: 200, k: 10},
{name: "english_top30", n: 200, words: 200, k: 30},
{name: "mixed_top10", n: 200, words: 200, k: 10, chinese: true},
{name: "mixed_top30", n: 200, words: 200, k: 30, chinese: true},
{name: "top1", n: 200, words: 200, k: 1},
} {
b.Run(tc.name, func(b *testing.B) {
results := mmrPassageCorpus(tc.n, tc.words, tc.chinese)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
SelectMMR(ctx, results, tc.k, DefaultMMRLambda)
}
})
}
}
+121
View File
@@ -0,0 +1,121 @@
package reranking
import (
"context"
"fmt"
"academy/internal/logger"
"academy/internal/tracing/langfuse"
"academy/internal/types"
)
// Observe selection in the shared implementation: agent tools and quick answers
// must expose the same decisions, including early exits and model-error fallback.
func recordSelection(ctx context.Context, input []*types.SearchResult, res *Result, opts Options,
scoredAsImage map[int]bool,
) {
out := summarizeSelection(input, res, opts, scoredAsImage)
const name = "diagnostics.rerank.selection"
logger.GetLogger(ctx).WithFields(logger.Fields(out)).Info(name)
_, span := langfuse.GetManager().StartSpan(ctx, langfuse.SpanOptions{
Name: name,
Metadata: map[string]interface{}{
"observation_kind": "diagnostic", "sample_scope": "image_vectors",
},
})
span.Finish(out, nil, nil)
}
func summarizeSelection(input []*types.SearchResult, res *Result, opts Options,
scoredAsImage map[int]bool,
) map[string]interface{} {
// Candidates retain input pointers. Final rows are copies, so use the
// returned input indices to distinguish retained and rejected inputs.
candidates := make(map[*types.SearchResult]int, len(res.Candidates))
for i, r := range res.Candidates {
candidates[r] = i
}
returned := make(map[int]*types.SearchResult, len(res.Indices))
for i, index := range res.Indices {
returned[index] = res.Results[i]
}
modelScores := make(map[int]float64, len(res.ModelScores))
for _, score := range res.ModelScores {
modelScores[score.Index] = score.RelevanceScore
}
passed := make(map[string]bool, len(res.Scored))
for _, r := range res.Scored {
passed[r.ID] = true
}
inputTypes, candidateTypes, outputTypes := map[string]int{}, map[string]int{}, map[string]int{}
for _, r := range res.Candidates {
candidateTypes[r.ChunkType]++
}
for _, r := range res.Results {
if r != nil {
outputTypes[r.ChunkType]++
}
}
images := make([]map[string]interface{}, 0)
decisions := map[string]int{}
imageCount := 0
for i, r := range input {
if r == nil {
continue
}
inputTypes[r.ChunkType]++
if !isImageVectorHit(r) {
continue
}
imageCount++
pos, candidate := candidates[r]
score, hasScore := modelScores[pos]
decision := "candidate_cap_or_empty_passage"
if kept, ok := returned[i]; ok {
decision = "kept"
if res.Diagnostics.Outcome == types.RerankOutcomeModelError {
decision = "model_error_fallback"
} else if kept.Metadata[types.MetadataKeptBy] == types.KeptByImageVector {
decision = "image_vector_fallback"
}
} else if candidate {
switch {
case !hasScore:
decision = "no_model_score"
case passed[r.ID]:
decision = "top_k_mmr_cut"
default:
decision = "rerank_rejected"
}
}
decisions[decision]++
if len(images) >= 10 {
continue
}
row := map[string]interface{}{
"input_rank": i + 1, "chunk_id": r.ID, "knowledge_id": r.KnowledgeID,
"vector_score": fmt.Sprintf("%.4f", r.VectorScore),
"retrieval_score": fmt.Sprintf("%.4f", r.Score), "decision": decision,
}
if candidate && hasScore {
row["model_score"] = fmt.Sprintf("%.4f", score)
row["scored_as"] = "text"
if scoredAsImage[pos] {
row["scored_as"] = "image"
}
}
images = append(images, row)
}
return map[string]interface{}{
"input_count": len(input), "candidate_count": len(res.Candidates), "output_count": len(res.Results),
"input_chunk_types": inputTypes, "candidate_chunk_types": candidateTypes, "output_chunk_types": outputTypes,
"outcome": res.Diagnostics.Outcome, "images_scored": res.Diagnostics.ImagesScored,
"images_kept_by_vector": res.Diagnostics.ImagesKept, "image_decision_counts": decisions,
"image_samples": images, "image_samples_truncated": imageCount - len(images),
// Keyword ordering and explicit scopes may use -Inf. Strings are JSON safe.
"threshold": fmt.Sprint(opts.Threshold), "effective_threshold": fmt.Sprint(res.Diagnostics.EffectiveThreshold),
"fallback_min_score": fmt.Sprint(opts.FallbackMinScore), "image_keep_score": fmt.Sprint(opts.ImageKeepScore),
"max_candidates": opts.MaxCandidates, "top_k": opts.TopK,
"top_model_score": fmt.Sprint(res.Diagnostics.TopScore),
}
}
+55
View File
@@ -0,0 +1,55 @@
package reranking
import (
"context"
"encoding/json"
"errors"
"math"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestSelectionDiagnosticsExplainRejectedAndProtectedImages(t *testing.T) {
input := []*types.SearchResult{
imageHit("weak", "private image caption", 0.21, 0),
imageHit("protected", "another caption", 0.4, 0),
}
opts := Options{Threshold: 0.3, FallbackMinScore: 0.15, ImageKeepScore: 0.25}
res := Rerank(context.Background(), &textScorer{}, "q", input, opts)
out := summarizeSelection(input, res, opts, nil)
require.Equal(t, map[string]int{"rerank_rejected": 1, "image_vector_fallback": 1}, out["image_decision_counts"])
require.Equal(t, map[string]int{"image_vector": 2}, out["input_chunk_types"])
require.Equal(t, map[string]int{"image_vector": 1}, out["output_chunk_types"])
rows := out["image_samples"].([]map[string]interface{})
require.Equal(t, "0.2100", rows[0]["vector_score"])
require.Equal(t, "0.0000", rows[0]["model_score"])
require.Equal(t, "text", rows[0]["scored_as"])
b, err := json.Marshal(out)
require.NoError(t, err)
require.NotContains(t, string(b), "private image caption")
}
func TestSelectionDiagnosticsExplainModelErrorAndAllowNonfiniteThresholds(t *testing.T) {
input := []*types.SearchResult{imageHit("image", "caption", 0.3, 0)}
opts := Options{Threshold: math.Inf(-1), FallbackMinScore: math.Inf(-1)}
res := Rerank(context.Background(), &textScorer{err: errors.New("offline")}, "q", input, opts)
out := summarizeSelection(input, res, opts, nil)
require.Equal(t, map[string]int{"model_error_fallback": 1}, out["image_decision_counts"])
require.Equal(t, "-Inf", out["threshold"])
_, err := json.Marshal(out)
require.NoError(t, err)
}
func TestSelectionDiagnosticsDistinguishTopKFromModelRejection(t *testing.T) {
input := []*types.SearchResult{
imageHit("first", "first", 0.4, 0), imageHit("second", "second", 0.3, 0),
}
opts := Options{Threshold: 0.3, TopK: 1}
model := &textScorer{scores: map[string]float64{"first": 0.9, "second": 0.8}}
res := Rerank(context.Background(), model, "q", input, opts)
out := summarizeSelection(input, res, opts, map[int]bool{0: true})
require.Equal(t, map[string]int{"kept": 1, "top_k_mmr_cut": 1}, out["image_decision_counts"])
require.Equal(t, "image", out["image_samples"].([]map[string]interface{})[0]["scored_as"])
}
+236
View File
@@ -0,0 +1,236 @@
package reranking
import (
"context"
"encoding/json"
"regexp"
"strings"
"academy/internal/logger"
"academy/internal/types"
)
// --- Passage cleaning for rerank ---
//
// Rerank models work on semantic text similarity. Markdown formatting, raw URLs,
// image references, table separators, and other structural syntax are noise that
// can dilute the semantic signal. The functions below strip this noise before
// passages are sent to the rerank model.
var (
// reMarkdownImage matches ![alt](url) — the entire construct is noise.
// URL group supports one level of balanced parentheses.
reMarkdownImage = regexp.MustCompile(`!\[[^\]]*\]\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`)
// reLinkedImage matches [![alt](img_url)](link_url) — unwrap to ![alt](img_url)
// so that the subsequent reMarkdownImage pass can remove the image.
reLinkedImage = regexp.MustCompile(
`\[!\[([^\]]*)\]\(([^()\s]*(?:\([^)]*\)[^()\s]*)*)\)\]` +
`\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`,
)
// reMarkdownLink matches [text](url) — we keep the text, drop the URL.
// URL group supports one level of balanced parentheses.
reMarkdownLink = regexp.MustCompile(`\[([^\]]+)\]\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`)
// reRawURL matches standalone http(s) URLs.
reRawURL = regexp.MustCompile(`https?://[^\s)\]>]+`)
// reLatexBlock captures the semantic body of block-level LaTeX ($$...$$).
reLatexBlock = regexp.MustCompile(`(?s)\$\$(.*?)\$\$`)
// reTableSep matches table separator rows like |---|---|.
// Uses [ \t] instead of \s to avoid consuming newlines across rows.
reTableSep = regexp.MustCompile(`(?m)^[ \t]*\|[ \t:|-]+\|[ \t]*$`)
// reTableRow matches markdown table data rows like | col1 | col2 |.
// Uses [ \t] instead of \s to avoid consuming newlines across rows.
reTableRow = regexp.MustCompile(`(?m)^[ \t]*\|(.+?)\|[ \t]*$`)
// reHeadingPrefix matches leading # markers in headings.
reHeadingPrefix = regexp.MustCompile(`(?m)^#{1,6}\s+`)
// reBlockquote matches leading > markers.
reBlockquote = regexp.MustCompile(`(?m)^>\s?`)
// reBoldItalic3 matches ***text*** wrappers (must come before 2 and 1).
reBoldItalic3 = regexp.MustCompile(`\*{3}(.+?)\*{3}`)
// reBoldItalic2 matches **text** wrappers.
reBoldItalic2 = regexp.MustCompile(`\*{2}(.+?)\*{2}`)
// reBoldItalic1 matches *text* wrappers.
reBoldItalic1 = regexp.MustCompile(`\*(.+?)\*`)
// reExcessiveNewlines collapses 3+ consecutive newlines into 2.
reExcessiveNewlines = regexp.MustCompile(`\n{3,}`)
// reListMarker matches unordered (- , * ) and ordered (1. ) list prefixes.
reListMarker = regexp.MustCompile(`(?m)^[\t ]*(?:[-*+]|\d+\.)\s+`)
// reHTMLTag matches HTML tags like <br>, <div class="...">, etc.
reHTMLTag = regexp.MustCompile(`</?[a-zA-Z][^>]*>`)
)
// CleanPassage strips markdown/structural noise from text to produce a clean
// semantic passage for the rerank model. The cleaning is designed to preserve
// all meaningful semantic content while removing formatting that would
// confuse text-similarity scoring.
func CleanPassage(text string) string {
var out, prose strings.Builder
var fenceChar byte
fenceLength := 0
flushProse := func() {
if prose.Len() == 0 {
return
}
out.WriteString(cleanPassageProse(prose.String()))
prose.Reset()
}
// Keep fenced code separate from prose throughout cleaning. Unwrapping
// first would let later passes delete XML, URLs and operators in code.
for line := range strings.SplitAfterSeq(text, "\n") {
marker, length, tail := passageFence(line)
if fenceLength == 0 {
if length < 3 || (marker == '`' && strings.ContainsRune(tail, '`')) {
prose.WriteString(line)
continue
}
flushProse()
fenceChar, fenceLength = marker, length
} else if marker == fenceChar && length >= fenceLength && strings.Trim(tail, " \t\r\n") == "" {
fenceLength = 0
} else {
out.WriteString(line)
}
}
flushProse()
return strings.TrimSpace(out.String())
}
// passageFence recognizes a top-level fence with up to three leading spaces.
// Matching type/length and a whitespace-only closing tail follow CommonMark
// 4.5. This helper does not recognize container, indented or inline code.
func passageFence(line string) (marker byte, length int, tail string) {
trimmed := strings.TrimLeft(line, " ")
if len(line)-len(trimmed) > 3 || len(trimmed) == 0 {
return 0, 0, ""
}
marker = trimmed[0]
if marker != '`' && marker != '~' {
return 0, 0, ""
}
for length < len(trimmed) && trimmed[length] == marker {
length++
}
return marker, length, trimmed[length:]
}
// cleanPassageProse leaves boundary whitespace intact so code and surrounding
// text retain their line boundaries when the cleaned segments are assembled.
func cleanPassageProse(text string) string {
// 2. Unwrap LaTeX blocks so formula-only candidates remain rerankable.
text = reLatexBlock.ReplaceAllString(text, "$1")
// 3. Remove HTML tags
text = reHTMLTag.ReplaceAllString(text, "")
// 3.5. Unwrap nested [![alt](img_url)](link_url) → ![alt](img_url)
// so that the next step removes the full construct cleanly.
text = reLinkedImage.ReplaceAllString(text, "![$1]($2)")
// 4. Remove markdown image references entirely
text = reMarkdownImage.ReplaceAllString(text, "")
// 5. Convert markdown links to just their display text
text = reMarkdownLink.ReplaceAllString(text, "$1")
// 6. Remove standalone raw URLs
text = reRawURL.ReplaceAllString(text, "")
// 7. Remove table separator rows
text = reTableSep.ReplaceAllString(text, "")
// 7.5. Convert table data rows to plain text (strip | delimiters)
text = reTableRow.ReplaceAllStringFunc(text, func(match string) string {
inner := reTableRow.FindStringSubmatch(match)
if len(inner) < 2 {
return match
}
cells := strings.Split(inner[1], "|")
var parts []string
for _, cell := range cells {
cell = strings.TrimSpace(cell)
if cell != "" {
parts = append(parts, cell)
}
}
return strings.Join(parts, ", ")
})
// 8. Strip heading markers but keep heading text
text = reHeadingPrefix.ReplaceAllString(text, "")
// 9. Strip blockquote markers
text = reBlockquote.ReplaceAllString(text, "")
// 10. Unwrap bold/italic markers, keeping inner text (order: *** before ** before *)
text = reBoldItalic3.ReplaceAllString(text, "$1")
text = reBoldItalic2.ReplaceAllString(text, "$1")
text = reBoldItalic1.ReplaceAllString(text, "$1")
// 11. Strip list markers
text = reListMarker.ReplaceAllString(text, "")
// 12. Collapse excessive newlines
text = reExcessiveNewlines.ReplaceAllString(text, "\n\n")
return text
}
// EnrichedPassage is the cleaned chunk body plus the image captions, OCR text
// and generated questions attached to it. MMR compares candidates on this
// text, so chunks of one document are not made similar by a shared title.
func EnrichedPassage(ctx context.Context, result *types.SearchResult) string {
combinedText := CleanPassage(result.Content)
var enrichments []string
// An image OCR or caption chunk's body is that same text, and its
// image_info repeats it; appending it again doubled the passage.
body := strings.TrimSpace(result.Content)
addImageText := func(text string) {
if text != "" && strings.TrimSpace(text) != body {
enrichments = append(enrichments, text)
}
}
if result.ImageInfo != "" {
var imageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos); err != nil {
logger.Warnf(ctx, "[Rerank] Failed to parse image info of chunk %s: %v", result.ID, err)
} else {
for _, img := range imageInfos {
addImageText(img.Caption)
addImageText(img.OCRText)
}
}
}
if len(result.ChunkMetadata) > 0 {
var docMeta types.DocumentChunkMetadata
if err := json.Unmarshal(result.ChunkMetadata, &docMeta); err != nil {
logger.Warnf(ctx, "[Rerank] Failed to parse chunk metadata of chunk %s: %v", result.ID, err)
} else if questionStrings := docMeta.GetQuestionStrings(); len(questionStrings) > 0 {
enrichments = append(enrichments, strings.Join(questionStrings, "; "))
}
}
if len(enrichments) == 0 {
return combinedText
}
if combinedText != "" {
combinedText += "\n\n"
}
return combinedText + strings.Join(enrichments, "\n")
}
// ModelPassage is the text the rerank model scores: the document title
// followed by the enriched chunk. A chunk rarely restates what its document
// is about, so without the title a passage from "Show HN: Echo - ... using
// open-weight models" scored 0.002 against "Echo open-weight models reduce
// cost" and 0.45 with it. FAQ entries carry their own question instead.
//
// An empty enriched body stays empty: a title alone is not evidence that
// the chunk answers anything.
//
// The chunk's heading breadcrumb (ContextHeader) goes between the two for the
// same reason: it was embedded with the chunk, so vector search can find
// "7 天内可申请" under "## 退款政策" while a model scoring the bare body
// rejects it.
func ModelPassage(ctx context.Context, result *types.SearchResult) string {
passage := EnrichedPassage(ctx, result)
if strings.TrimSpace(passage) == "" || result.ChunkType == string(types.ChunkTypeFAQ) {
return passage
}
if header := strings.TrimSpace(result.ContextHeader); header != "" {
passage = header + "\n\n" + passage
}
if title := strings.TrimSpace(result.KnowledgeTitle); title != "" {
passage = title + "\n\n" + passage
}
return passage
}
+132
View File
@@ -0,0 +1,132 @@
package reranking
import (
"context"
"testing"
"academy/internal/types"
)
func TestCleanPassagePreservesFencedCode(t *testing.T) {
t.Parallel()
tests := []struct {
name, input, want string
}{
{
name: "XML-only evidence must not become empty",
input: "```xml\n<refund-policy days=\"7\"/>\n```",
want: "<refund-policy days=\"7\"/>",
},
{
name: "URLs and formatting-like operators are code",
input: "```python\nurl = \"https://api.example.com/v1\"\nvalue = 2 ** 3 ** 2\n```",
want: "url = \"https://api.example.com/v1\"\nvalue = 2 ** 3 ** 2",
},
{
name: "literal Markdown is code",
input: "```markdown\n# Heading\n- item\n| A | B |\n| --- | --- |\n" +
"![alt](image.png)\n[label](https://example.com)\n```",
want: "# Heading\n- item\n| A | B |\n| --- | --- |\n" +
"![alt](image.png)\n[label](https://example.com)",
},
{
name: "code blank lines and math delimiters survive",
input: "```text\nbefore\n\n\n\nafter $$price$$\n```",
want: "before\n\n\n\nafter $$price$$",
},
{
name: "longer outer fence keeps shorter inner fence",
input: "````markdown\n```xml\n<policy/>\n```\n````",
want: "```xml\n<policy/>\n```",
},
{
name: "tilde fences",
input: "~~~xml\n<policy/>\n~~~",
want: "<policy/>",
},
{
name: "mismatched delimiter is code",
input: "```text\n~~~\n<policy/>\n```",
want: "~~~\n<policy/>",
},
{
name: "closing fence cannot carry an info string",
input: "```text\n```not-a-close\n<policy/>\n```",
want: "```not-a-close\n<policy/>",
},
{
name: "longer closing fence",
input: "```xml\n<policy/>\n`````",
want: "<policy/>",
},
{
name: "unclosed fence protects remaining code",
input: "```xml\n<policy/>\nhttps://api.example.com",
want: "<policy/>\nhttps://api.example.com",
},
{
name: "CRLF code lines",
input: "```xml\r\n<one/>\r\n<two/>\r\n```\r\n",
want: "<one/>\r\n<two/>",
},
{
name: "indented fence and CRLF closing whitespace",
input: " ~~~xml\r\n<policy/>\r\n ~~~ \t\r\n",
want: "<policy/>",
},
{
name: "only prose is cleaned between code blocks",
input: "## Example\n```xml\n<one/>\n```\n**Explanation** [docs](https://example.com)\n" +
"~~~shell\ncurl https://api.example.com\n~~~\n> End",
want: "Example\n<one/>\nExplanation docs\ncurl https://api.example.com\nEnd",
},
{
name: "inline triple backticks do not open a block",
input: "Text ```not a block\n**bold**",
want: "Text ```not a block\nbold",
},
{
name: "four-space indented fences are not fenced blocks",
input: " ```xml\n<policy/>\n ```",
want: "```xml\n\n ```",
},
{
name: "backticks in a backtick info string invalidate the opening",
input: "```bad`info\n**bold**",
want: "```bad`info\nbold",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := CleanPassage(tt.input); got != tt.want {
t.Errorf("CleanPassage() = %q, want %q", got, tt.want)
}
})
}
}
func TestRerankReceivesFencedCodeWithoutMarkdownCleaning(t *testing.T) {
t.Parallel()
content := "```xml\n<refund-policy days=\"7\"/>\n```"
model := &stubReranker{scores: []float64{0.9}}
input := []*types.SearchResult{{
ID: "policy", Content: content, KnowledgeTitle: "API policy",
ContextHeader: "Refunds", ChunkType: string(types.ChunkTypeText), Score: 0.8,
}}
result := Rerank(context.Background(), model, "refund policy days", input,
Options{Threshold: 0.3})
want := "API policy\n\nRefunds\n\n<refund-policy days=\"7\"/>"
if len(model.documents) != 1 || model.documents[0] != want {
t.Fatalf("model received %q, want one passage %q", model.documents, want)
}
if len(result.Results) != 1 || result.Results[0].ID != "policy" {
t.Fatalf("code-only candidate was dropped: %+v", result)
}
if input[0].Content != content || result.Results[0].Content != content {
t.Fatal("passage cleaning changed the stored/returned chunk content")
}
if got := EnrichedPassage(context.Background(), input[0]); got != "<refund-policy days=\"7\"/>" {
t.Fatalf("MMR enrichment lost the code evidence: %q", got)
}
}
+191
View File
@@ -0,0 +1,191 @@
package reranking
import (
"context"
"encoding/json"
"strings"
"testing"
"academy/internal/types"
)
func TestGetEnrichedPassageKeepsQuestionsFromEarlierRevision(t *testing.T) {
metadata, err := json.Marshal(types.DocumentChunkMetadata{
GeneratedQuestionsRevision: 1,
GeneratedQuestions: []types.GeneratedQuestion{{
ID: "old", Question: "question generated before the edit",
}},
})
if err != nil {
t.Fatal(err)
}
passage := EnrichedPassage(context.Background(), &types.SearchResult{
Content: "edited chunk body",
ChunkMetadata: types.JSON(metadata),
})
if !strings.Contains(passage, "question generated before the edit") {
t.Fatalf("earlier generated question was excluded from rerank passage: %q", passage)
}
}
func TestGetEnrichedPassageKeepsCodeAndMathCandidates(t *testing.T) {
tests := []struct {
name string
content string
want string
}{
{
name: "code only",
content: "```go\nfunc answer() int { return 42 }\n```",
want: "func answer() int { return 42 }",
},
{
name: "math only",
content: "$$\nE = mc^2\n$$",
want: "E = mc^2",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
passage := EnrichedPassage(context.Background(), &types.SearchResult{Content: tt.content})
if strings.TrimSpace(passage) == "" {
t.Fatal("semantic-only candidate was removed from the rerank passage")
}
if !strings.Contains(passage, tt.want) {
t.Fatalf("rerank passage %q does not preserve %q", passage, tt.want)
}
})
}
}
func TestCleanPassageForRerank(t *testing.T) {
tests := []struct {
name string
input string
expect string
}{
{
name: "plain text unchanged",
input: "这是一段普通的文本内容",
expect: "这是一段普通的文本内容",
},
{
name: "remove markdown images",
input: "前文 ![图片说明](https://example.com/img.png) 后文",
expect: "前文 后文",
},
{
name: "convert markdown links to text",
input: "请参考 [官方文档](https://docs.example.com) 了解详情",
expect: "请参考 官方文档 了解详情",
},
{
name: "remove standalone URLs",
input: "访问 https://example.com/path?q=1&b=2 获取更多信息",
expect: "访问 获取更多信息",
},
{
name: "unwrap code blocks",
input: "示例代码:\n```python\nprint('hello')\n```\n以上是示例",
expect: "示例代码:\nprint('hello')\n以上是示例",
},
{
name: "unwrap LaTeX blocks",
input: "公式如下 $$E=mc^2$$ 其中E是能量",
expect: "公式如下 E=mc^2 其中E是能量",
},
{
name: "remove table separator rows and convert data rows",
input: "| 名称 | 值 |\n| --- | --- |\n| A | 1 |",
expect: "名称, 值\n\nA, 1",
},
{
name: "strip heading markers",
input: "## 第二章 概述\n### 2.1 背景",
expect: "第二章 概述\n2.1 背景",
},
{
name: "strip blockquote markers",
input: "> 这是一段引用\n> 第二行引用",
expect: "这是一段引用\n第二行引用",
},
{
name: "unwrap bold and italic",
input: "这是 **加粗** 和 *斜体* 以及 ***粗斜体*** 文本",
expect: "这是 加粗 和 斜体 以及 粗斜体 文本",
},
{
name: "strip list markers",
input: "- 项目一\n- 项目二\n1. 有序一\n2. 有序二",
expect: "项目一\n项目二\n有序一\n有序二",
},
{
name: "remove HTML tags",
input: "文本<br>换行<div class=\"test\">内容</div>结尾",
expect: "文本换行内容结尾",
},
{
name: "collapse excessive newlines",
input: "段落一\n\n\n\n\n段落二",
expect: "段落一\n\n段落二",
},
{
name: "combined real-world passage",
input: `## 产品介绍
这是一个 **重要的** 产品。详见 [产品页面](https://example.com/product)。
![产品截图](images/product.png)
> 用户评价:非常好用
- 功能一
- 功能二
` + "```json\n{\"key\": \"value\"}\n```",
expect: "产品介绍\n\n这是一个 重要的 产品。详见 产品页面。\n\n用户评价:非常好用\n\n功能一\n功能二\n\n{\"key\": \"value\"}",
},
{
name: "convert table data rows to plain text",
input: "| col1 | col2 | col3 |",
expect: "col1, col2, col3",
},
{
name: "multi-row table fully converted",
input: "| Header1 | Header2 |\n| --- | --- |\n| data1 | data2 |\n| data3 | data4 |",
expect: "Header1, Header2\n\ndata1, data2\ndata3, data4",
},
{
name: "table-only passage becomes empty after separator removal",
input: "| --- | --- |",
expect: "",
},
{
name: "whitespace-only after cleaning",
input: " \n\n ",
expect: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := CleanPassage(tt.input)
if got != tt.expect {
t.Errorf("CleanPassage():\ngot: %q\nexpect: %q", got, tt.expect)
}
})
}
}
func TestModelPassage_includesHeadingBreadcrumb(t *testing.T) {
t.Parallel()
got := ModelPassage(context.Background(), &types.SearchResult{
Content: "7 天内可申请", KnowledgeTitle: "售后手册", ContextHeader: "退款政策 > 申请条件",
ChunkType: string(types.ChunkTypeText),
})
if got != "售后手册\n\n退款政策 > 申请条件\n\n7 天内可申请" {
t.Fatalf("passage = %q", got)
}
}
+389
View File
@@ -0,0 +1,389 @@
// Package reranking is the single rerank stage shared by the chat pipeline,
// the agent search_knowledge tool and the retrieval APIs: passage building,
// model scoring, threshold filtering with degradation, composite scoring and
// MMR selection.
package reranking
import (
"context"
"maps"
"math"
"sort"
"strconv"
"strings"
"unicode/utf8"
"academy/internal/logger"
"academy/internal/models/rerank"
"academy/internal/types"
)
const (
// DefaultThreshold is the minimum rerank score used when no configuration
// supplies one. It matches RetrievalConfig.GetEffectiveRerankThreshold.
DefaultThreshold = 0.2
// DefaultFallbackMinScore is the score the best candidate needs to be kept
// when nothing passes the threshold. Below it, returning nothing beats
// forcing an irrelevant result on the caller.
DefaultFallbackMinScore = 0.15
// A threshold above degradeFloor that rejects every candidate is retried
// at degradeFactor times itself, but never below degradeFloor.
degradeFloor = 0.3
degradeFactor = 0.7
// DefaultMaxCandidates bounds how many candidates the chat pipeline and
// the agent tool send to the rerank model. Query expansion and
// per-document or per-tag targets each add a full retrieval list, and
// every candidate is a billed passage and a share of the latency.
DefaultMaxCandidates = 200
)
// FallbackMinScore returns the score the best candidate needs to survive an
// all-rejecting threshold. When the caller explicitly scoped the search to a
// tag or document set, its best candidate is kept regardless, rather than
// letting a global threshold erase the whole authoritative scope. Model
// scores can be negative, so "regardless" is -Inf rather than 0.
func FallbackMinScore(explicitScope bool) float64 {
if explicitScope {
return math.Inf(-1)
}
return DefaultFallbackMinScore
}
// Options configures one rerank run.
type Options struct {
// Threshold is the minimum model score a candidate needs.
Threshold float64
// TopK, when positive, MMR-selects at most TopK results. Otherwise every
// candidate that passed the threshold is returned, best first.
TopK int
// FallbackMinScore is the score the best candidate needs to be kept when
// nothing passes the threshold. See FallbackMinScore().
FallbackMinScore float64
// MaxCandidates, when positive, reranks only the MaxCandidates rows with
// the highest retrieval score. Retrieval scores share one [0, 1] scale
// across searches, so the cut keeps the strongest candidates of each.
MaxCandidates int
// FAQScoreBoost, when above 1, multiplies the composite score of FAQ
// entries, capped at 1 so scores stay on the [0, 1] scale. FAQs tied at
// the cap are ordered by their pre-boost score. Compare absolute
// thresholds against PreBoostScore.
FAQScoreBoost float64
// LoadImage reads the image an image_vector hit shows. With it, a model
// that reads images scores those hits by their image; without it they
// are scored by their text like any other row.
LoadImage func(ctx context.Context, r *types.SearchResult) ([]byte, error)
// ImageKeepScore, when positive, keeps a pictorial image_vector hit a
// text reranker rejected if its VectorScore reaches this, at most
// maxKeptImages of them, after the ranked results and marked with
// types.MetadataKeptBy. A text reranker cannot judge what a caption leaves
// out; the vector can. Callers pass the text vector threshold or more.
// Kept results ride outside TopK; see types.MetadataKeptBy.
ImageKeepScore float64
}
// Result is the outcome of a rerank run.
type Result struct {
// Results are the returned rows, best first. They are copies carrying the
// composite score and base_score / model_score metadata; the input rows
// are never modified. On a model error they are the input rows unchanged.
Results []*types.SearchResult
// Indices[i] is the position of Results[i] in the input slice.
Indices []int
// Diagnostics summarises the run for API callers and logs.
Diagnostics types.RerankDiagnostics
// Candidates are the input rows with a non-empty passage, in input
// order; Passages are what the model scored for them. ModelScores index
// into Candidates. Scored are the rows that passed the threshold, with
// composite scores, before MMR. Kept for tracing.
Candidates []*types.SearchResult
Passages []string
ModelScores []rerank.RankResult
Scored []*types.SearchResult
}
// Rerank scores results against query with model and returns the rows that
// pass opts, best first. A failed model call is not an error: the result
// carries the input rows unchanged and a model_error outcome, so callers can
// degrade to the retrieval order.
func Rerank(
ctx context.Context,
model rerank.Reranker,
query string,
results []*types.SearchResult,
opts Options,
) *Result {
res := &Result{
Diagnostics: types.RerankDiagnostics{
Threshold: opts.Threshold,
EffectiveThreshold: opts.Threshold,
},
}
var scoredAsImage map[int]bool
defer func() { recordSelection(ctx, results, res, opts, scoredAsImage) }()
keep := topByScore(results, opts.MaxCandidates)
candidateIdx := make([]int, 0, len(results))
for i, r := range results {
if r == nil || (keep != nil && !keep[i]) {
continue
}
passage := ModelPassage(ctx, r)
if strings.TrimSpace(passage) == "" {
continue
}
candidateIdx = append(candidateIdx, i)
res.Candidates = append(res.Candidates, r)
res.Passages = append(res.Passages, passage)
}
res.Diagnostics.CandidateCount = len(res.Candidates)
if len(res.Candidates) == 0 {
res.Diagnostics.Outcome = types.RerankOutcomeNoCandidates
return res
}
fitPassages(ctx, res.Passages, rerank.MaxPassageRunes(model, query))
imagePositions, images := imageCandidates(ctx, model, res.Candidates, opts)
scores, scoredAsImage, err := scoreCandidates(ctx, model, query, res.Passages, imagePositions, images)
res.Diagnostics.ImagesScored = len(scoredAsImage)
if err != nil {
logger.Warnf(ctx, "[Rerank] Model call failed, keeping retrieval order: %v", err)
res.Diagnostics.Outcome = types.RerankOutcomeModelError
res.Diagnostics.Error = err.Error()
res.Results = results
res.Indices = make([]int, len(results))
for i := range results {
res.Indices[i] = i
}
res.Diagnostics.ResultCount = len(results)
return res
}
// Drop out-of-range indices once so nothing below has to re-check them.
valid := scores[:0:0]
for _, s := range scores {
if s.Index >= 0 && s.Index < len(res.Candidates) {
valid = append(valid, s)
}
}
res.ModelScores = valid
res.Diagnostics.Applied = true
top, hasTop := bestScore(valid)
if hasTop {
res.Diagnostics.TopScore = top.RelevanceScore
}
passing, outcome, effective := applyThreshold(valid, opts)
res.Diagnostics.Outcome = outcome
res.Diagnostics.EffectiveThreshold = effective
scored := make([]*types.SearchResult, 0, len(passing))
scoredIdx := make([]int, 0, len(passing))
for _, rr := range passing {
scored = append(scored, scoredCopy(res.Candidates[rr.Index], rr.RelevanceScore, opts.FAQScoreBoost))
scoredIdx = append(scoredIdx, candidateIdx[rr.Index])
}
order := make([]int, len(scored))
for i := range order {
order[i] = i
}
sort.SliceStable(order, func(a, b int) bool {
sa, sb := scored[order[a]], scored[order[b]]
if sa.Score != sb.Score {
return sa.Score > sb.Score
}
// Boosted FAQs capped at 1 tie; keep them in relevance order.
return PreBoostScore(sa) > PreBoostScore(sb)
})
res.Scored = make([]*types.SearchResult, len(order))
sortedIdx := make([]int, len(order))
for i, o := range order {
res.Scored[i] = scored[o]
sortedIdx[i] = scoredIdx[o]
}
picks := make([]int, len(res.Scored))
for i := range picks {
picks[i] = i
}
if opts.TopK > 0 {
picks = SelectMMR(ctx, res.Scored, min(opts.TopK, len(res.Scored)), DefaultMMRLambda)
}
res.Results = make([]*types.SearchResult, 0, len(picks))
res.Indices = make([]int, 0, len(picks))
for _, p := range picks {
res.Results = append(res.Results, res.Scored[p])
res.Indices = append(res.Indices, sortedIdx[p])
}
for _, k := range keptImages(ctx, res.Candidates, valid, passing, scoredAsImage, opts) {
kept := scoredCopy(res.Candidates[k.Index], k.RelevanceScore, opts.FAQScoreBoost)
kept.Metadata[types.MetadataKeptBy] = types.KeptByImageVector
res.Results = append(res.Results, kept)
res.Indices = append(res.Indices, candidateIdx[k.Index])
res.Diagnostics.ImagesKept++
}
res.Diagnostics.ResultCount = len(res.Results)
logger.Infof(ctx, "[Rerank] %d candidates -> %d results, outcome=%s threshold=%.3f effective=%.3f top=%.4f",
len(res.Candidates), len(res.Results), outcome, opts.Threshold, effective, res.Diagnostics.TopScore)
return res
}
// topByScore returns the positions of the limit highest-scoring rows, or nil
// when limit is not positive or every row fits. Ties keep the earlier row.
// Graph hits are always kept outside the limit: they carry no retrieval score
// (CompositeScore substitutes the model score) and would otherwise always be
// cut; their number is bounded where they are added.
func topByScore(results []*types.SearchResult, limit int) map[int]bool {
if limit <= 0 || len(results) <= limit {
return nil
}
keep := make(map[int]bool, limit)
order := make([]int, 0, len(results))
for i, r := range results {
switch {
case r == nil:
case r.MatchType == types.MatchTypeGraph:
keep[i] = true
default:
order = append(order, i)
}
}
if len(order) <= limit {
return nil
}
sort.SliceStable(order, func(a, b int) bool { return results[order[a]].Score > results[order[b]].Score })
for _, i := range order[:limit] {
keep[i] = true
}
return keep
}
// fitPassages trims passages longer than limit runes (0 = no limit). A
// passage is the title, then the chunk body, then captions, OCR text and
// generated questions, so trimming the tail drops the least essential text
// first. Vendors reject an oversized document, and the protocol layer fails
// the whole request rather than truncate it, so a single chunk with a large
// screenshot's OCR text used to cost every candidate its rerank score.
func fitPassages(ctx context.Context, passages []string, limit int) {
if limit <= 0 {
return
}
trimmed := 0
for i, p := range passages {
if utf8.RuneCountInString(p) > limit {
passages[i] = string([]rune(p)[:limit])
trimmed++
}
}
if trimmed > 0 {
logger.Infof(ctx, "[Rerank] Trimmed %d passages to the model's %d-character limit", trimmed, limit)
}
}
// applyThreshold keeps the scores at or above opts.Threshold. When none
// pass, a threshold above degradeFloor is lowered once; when still none
// pass, the best candidate is kept if it reaches opts.FallbackMinScore.
func applyThreshold(
scores []rerank.RankResult,
opts Options,
) ([]rerank.RankResult, types.RerankOutcome, float64) {
threshold := opts.Threshold
if passing := filterScores(scores, threshold); len(passing) > 0 {
return passing, types.RerankOutcomeOK, threshold
}
if threshold > degradeFloor {
threshold = math.Max(threshold*degradeFactor, degradeFloor)
if passing := filterScores(scores, threshold); len(passing) > 0 {
return passing, types.RerankOutcomeThresholdDegraded, threshold
}
}
if top, ok := bestScore(scores); ok && top.RelevanceScore >= opts.FallbackMinScore {
return []rerank.RankResult{top}, types.RerankOutcomeFallbackTop1, threshold
}
return nil, types.RerankOutcomeAllBelowThreshold, threshold
}
func filterScores(scores []rerank.RankResult, threshold float64) []rerank.RankResult {
var out []rerank.RankResult
for _, s := range scores {
if s.RelevanceScore >= threshold {
out = append(out, s)
}
}
return out
}
// bestScore returns the highest score. Providers usually return scores
// sorted, but nothing guarantees it.
func bestScore(scores []rerank.RankResult) (rerank.RankResult, bool) {
if len(scores) == 0 {
return rerank.RankResult{}, false
}
top := scores[0]
for _, s := range scores[1:] {
if s.RelevanceScore > top.RelevanceScore {
top = s
}
}
return top, true
}
// CompositeScoreKey is the Metadata key holding a reranked row's composite
// score before any boost (FAQ boost here, wiki or memory boosts later in the
// chat pipeline) changes Score.
const CompositeScoreKey = "composite_score"
// scoredCopy returns a copy of r whose Score is the composite of the model
// score and its retrieval score, recording both in Metadata.
func scoredCopy(r *types.SearchResult, modelScore, faqBoost float64) *types.SearchResult {
c := *r
c.Metadata = maps.Clone(r.Metadata)
if c.Metadata == nil {
c.Metadata = make(map[string]string, 3)
}
base := r.Score
c.Metadata["base_score"] = strconv.FormatFloat(base, 'f', 4, 64)
c.Metadata["model_score"] = strconv.FormatFloat(modelScore, 'f', 4, 64)
c.Score = CompositeScore(&c, modelScore, base)
c.Metadata[CompositeScoreKey] = strconv.FormatFloat(c.Score, 'f', 4, 64)
if faqBoost > 1.0 && c.ChunkType == string(types.ChunkTypeFAQ) {
c.Metadata["faq_boosted"] = "true"
c.Metadata["faq_original_score"] = strconv.FormatFloat(c.Score, 'f', 4, 64)
c.Score = math.Min(c.Score*faqBoost, 1.0)
}
return &c
}
// CompositeScore blends the rerank model score with the retrieval score and a
// source weight, clamped to [0, 1]. Graph hits carry no retrieval score (they
// come from entity lookups, not similarity search), so the model score stands
// in for it rather than a made-up constant.
func CompositeScore(r *types.SearchResult, modelScore, baseScore float64) float64 {
sourceWeight := 1.0
if strings.EqualFold(r.KnowledgeSource, "web_search") {
sourceWeight = 0.95
}
if r.MatchType == types.MatchTypeGraph {
baseScore = modelScore
}
composite := 0.6*modelScore + 0.3*baseScore + 0.1*sourceWeight
return math.Min(math.Max(composite, 0), 1)
}
// PreBoostScore returns the score to compare against absolute thresholds such
// as the FAQ direct-answer threshold: the composite score before any boost
// when the row was reranked, and its retrieval score otherwise.
func PreBoostScore(r *types.SearchResult) float64 {
if r == nil {
return 0
}
if v, ok := r.Metadata[CompositeScoreKey]; ok {
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
}
return r.Score
}
+312
View File
@@ -0,0 +1,312 @@
package reranking
import (
"context"
"errors"
"math"
"strings"
"testing"
"academy/internal/models/rerank"
"academy/internal/types"
)
// stubReranker returns canned scores (or an error) without any network call.
type stubReranker struct {
scores []float64
err error
calls int
documents []string
}
func (s *stubReranker) Rerank(_ context.Context, _ string, documents []string) ([]rerank.RankResult, error) {
s.calls++
s.documents = documents
if s.err != nil {
return nil, s.err
}
out := make([]rerank.RankResult, 0, len(documents))
for i := range documents {
score := 0.0
if i < len(s.scores) {
score = s.scores[i]
}
out = append(out, rerank.RankResult{Index: i, RelevanceScore: score})
}
return out, nil
}
func (s *stubReranker) GetModelName() string { return "stub-rerank" }
func (s *stubReranker) GetModelID() string { return "stub-rerank-id" }
func rows(contents ...string) []*types.SearchResult {
out := make([]*types.SearchResult, len(contents))
for i, c := range contents {
out[i] = &types.SearchResult{ID: "c" + string(rune('1'+i)), Content: c, Score: 0.5}
}
return out
}
func ids(results []*types.SearchResult) string {
parts := make([]string, len(results))
for i, r := range results {
parts[i] = r.ID
}
return strings.Join(parts, ",")
}
func TestRerank_thresholdKeepsPassingBestFirst(t *testing.T) {
t.Parallel()
in := rows("alpha", "beta", "gamma")
res := Rerank(context.Background(), &stubReranker{scores: []float64{0.4, 0.9, 0.1}}, "q", in,
Options{Threshold: 0.3, FallbackMinScore: DefaultFallbackMinScore})
if got := ids(res.Results); got != "c2,c1" {
t.Fatalf("results = %s, want c2,c1", got)
}
if res.Indices[0] != 1 || res.Indices[1] != 0 {
t.Fatalf("indices = %v, want [1 0]", res.Indices)
}
d := res.Diagnostics
if !d.Applied || d.Outcome != types.RerankOutcomeOK || d.TopScore != 0.9 ||
d.CandidateCount != 3 || d.ResultCount != 2 {
t.Fatalf("diagnostics = %+v", d)
}
if res.Results[0].Metadata["model_score"] != "0.9000" || res.Results[0].Metadata["base_score"] != "0.5000" {
t.Fatalf("metadata = %v", res.Results[0].Metadata)
}
if want := 0.6*0.9 + 0.3*0.5 + 0.1; math.Abs(res.Results[0].Score-want) > 1e-9 {
t.Fatalf("composite = %v, want %v", res.Results[0].Score, want)
}
// Inputs are never modified.
if in[1].Score != 0.5 || in[1].Metadata != nil {
t.Fatalf("input row was mutated: %+v", in[1])
}
}
func TestRerank_degradesHighThresholdBeforeFallback(t *testing.T) {
t.Parallel()
// 0.5 rejects everything; degraded threshold is max(0.5*0.7, 0.3) = 0.35.
res := Rerank(context.Background(), &stubReranker{scores: []float64{0.36, 0.2}}, "q", rows("a", "b"),
Options{Threshold: 0.5, FallbackMinScore: DefaultFallbackMinScore})
if got := ids(res.Results); got != "c1" {
t.Fatalf("results = %s, want c1", got)
}
if res.Diagnostics.Outcome != types.RerankOutcomeThresholdDegraded ||
math.Abs(res.Diagnostics.EffectiveThreshold-0.35) > 1e-9 {
t.Fatalf("diagnostics = %+v", res.Diagnostics)
}
}
func TestRerank_fallbackTop1AndEmpty(t *testing.T) {
t.Parallel()
ctx := context.Background()
res := Rerank(ctx, &stubReranker{scores: []float64{0.05, 0.20}}, "q", rows("a", "b"),
Options{Threshold: 0.3, FallbackMinScore: DefaultFallbackMinScore})
if ids(res.Results) != "c2" || res.Diagnostics.Outcome != types.RerankOutcomeFallbackTop1 {
t.Fatalf("expected best candidate fallback, got %s %+v", ids(res.Results), res.Diagnostics)
}
res = Rerank(ctx, &stubReranker{scores: []float64{0.10, 0.04}}, "q", rows("a", "b"),
Options{Threshold: 0.3, FallbackMinScore: DefaultFallbackMinScore})
if len(res.Results) != 0 || res.Diagnostics.Outcome != types.RerankOutcomeAllBelowThreshold ||
res.Diagnostics.TopScore != 0.10 {
t.Fatalf("expected empty result, got %s %+v", ids(res.Results), res.Diagnostics)
}
// An explicit scope keeps its best candidate even with a negative score.
res = Rerank(ctx, &stubReranker{scores: []float64{-2, -1}}, "q", rows("a", "b"),
Options{Threshold: 0.3, FallbackMinScore: FallbackMinScore(true)})
if ids(res.Results) != "c2" {
t.Fatalf("explicit scope must keep its best candidate, got %s", ids(res.Results))
}
}
func TestRerank_modelErrorReturnsInputUnchanged(t *testing.T) {
t.Parallel()
in := rows("a", "b")
model := &stubReranker{err: errors.New("upstream 500")}
res := Rerank(context.Background(), model, "q", in, Options{Threshold: 0.3})
if res.Diagnostics.Outcome != types.RerankOutcomeModelError || res.Diagnostics.Applied ||
res.Diagnostics.Error != "upstream 500" {
t.Fatalf("diagnostics = %+v", res.Diagnostics)
}
if len(res.Results) != 2 || res.Results[0] != in[0] || res.Results[1] != in[1] {
t.Fatalf("expected the input rows, got %#v", res.Results)
}
if model.calls != 1 {
t.Fatalf("expected one model call, got %d", model.calls)
}
}
func TestRerank_skipsEmptyPassagesAndReportsNoCandidates(t *testing.T) {
t.Parallel()
model := &stubReranker{scores: []float64{0.9}}
res := Rerank(context.Background(), model, "q", rows(" ", "body"), Options{Threshold: 0.3})
if len(model.documents) != 1 || ids(res.Results) != "c2" || res.Indices[0] != 1 {
t.Fatalf("documents=%q results=%s indices=%v", model.documents, ids(res.Results), res.Indices)
}
model = &stubReranker{}
res = Rerank(context.Background(), model, "q", rows(""), Options{Threshold: 0.3})
if model.calls != 0 || res.Diagnostics.Outcome != types.RerankOutcomeNoCandidates {
t.Fatalf("calls=%d diagnostics=%+v", model.calls, res.Diagnostics)
}
}
func TestRerank_topKAppliesMMRAndFAQBoost(t *testing.T) {
t.Parallel()
in := rows("alpha beta", "gamma delta", "epsilon zeta")
in[2].ChunkType = string(types.ChunkTypeFAQ)
res := Rerank(context.Background(), &stubReranker{scores: []float64{0.9, 0.8, 0.7}}, "q", in,
Options{Threshold: 0.3, TopK: 2, FAQScoreBoost: 1.5})
if len(res.Results) != 2 || len(res.Scored) != 3 {
t.Fatalf("results=%d scored=%d", len(res.Results), len(res.Scored))
}
// The FAQ entry is boosted from 0.67 to 1.005, capped at 1, and ranks
// first; its pre-boost score stays available for absolute thresholds.
top := res.Results[0]
if top.ID != "c3" || top.Metadata["faq_boosted"] != "true" || math.Abs(top.Score-1.0) > 1e-9 {
t.Fatalf("FAQ boost not applied: %+v", top)
}
if got := PreBoostScore(top); math.Abs(got-0.67) > 1e-9 {
t.Fatalf("pre-boost score = %v, want 0.67", got)
}
}
// Strong FAQ entries are capped at 1 and tie; their order must still follow
// relevance, and the boost must not leave the [0, 1] scale.
func TestRerank_boostedFAQsKeepRelevanceOrder(t *testing.T) {
t.Parallel()
in := rows("faq weaker", "faq stronger")
for _, r := range in {
r.ChunkType = string(types.ChunkTypeFAQ)
}
res := Rerank(context.Background(), &stubReranker{scores: []float64{0.9, 0.95}}, "q", in,
Options{Threshold: 0.3, FAQScoreBoost: 1.5})
if len(res.Results) != 2 || res.Results[0].ID != "c2" {
t.Fatalf("boosted FAQs lost their order: %+v / %+v", res.Results[0], res.Results[1])
}
for _, r := range res.Results {
if r.Score > 1 {
t.Fatalf("boosted score %v exceeds 1", r.Score)
}
}
}
// Graph hits have no retrieval score; the model score stands in for it.
func TestCompositeScore_graphHitUsesModelScoreAsBase(t *testing.T) {
t.Parallel()
graph := &types.SearchResult{MatchType: types.MatchTypeGraph}
if got := CompositeScore(graph, 0.8, 0); math.Abs(got-(0.9*0.8+0.1)) > 1e-9 {
t.Fatalf("graph composite = %v", got)
}
vector := &types.SearchResult{MatchType: types.MatchTypeEmbedding}
if got := CompositeScore(vector, 0.8, 0); math.Abs(got-(0.6*0.8+0.1)) > 1e-9 {
t.Fatalf("vector composite = %v", got)
}
}
func TestPreBoostScore_fallsBackToScore(t *testing.T) {
t.Parallel()
if got := PreBoostScore(&types.SearchResult{Score: 0.42}); got != 0.42 {
t.Fatalf("PreBoostScore without rerank metadata = %v", got)
}
if got := PreBoostScore(nil); got != 0 {
t.Fatalf("PreBoostScore(nil) = %v", got)
}
}
// A chunk rarely names its document's subject, so the rerank model sees the
// document title; FAQ entries are scored on their own question.
func TestModelPassage_prefixesDocumentTitle(t *testing.T) {
t.Parallel()
model := &stubReranker{scores: []float64{0.5, 0.5, 0.5}}
Rerank(context.Background(), model, "q", []*types.SearchResult{
{
ID: "c1", Content: "allocate inference across **open-weight** models",
KnowledgeTitle: " Show HN: Echo ", ChunkType: string(types.ChunkTypeText),
},
{ID: "c2", Content: "What is Echo?", KnowledgeTitle: "FAQ set", ChunkType: string(types.ChunkTypeFAQ)},
{ID: "c3", Content: "untitled"},
}, Options{})
want := []string{"Show HN: Echo\n\nallocate inference across open-weight models", "What is Echo?", "untitled"}
for i, w := range want {
if model.documents[i] != w {
t.Fatalf("passage %d = %q, want %q", i, model.documents[i], w)
}
}
}
func TestFallbackMinScore(t *testing.T) {
t.Parallel()
if got := FallbackMinScore(false); got != DefaultFallbackMinScore {
t.Fatalf("default fallback minimum = %v", got)
}
if got := FallbackMinScore(true); !math.IsInf(got, -1) {
t.Fatalf("explicit-scope fallback minimum = %v, want -Inf", got)
}
}
// limitedReranker is a stubReranker whose vendor documents a passage limit.
type limitedReranker struct {
stubReranker
limit int
}
func (l *limitedReranker) MaxPassageRunes(string) int { return l.limit }
// An oversized passage used to fail the whole request, costing every
// candidate its score. Passages are now fitted to the documented limit,
// keeping the title and body ahead of the appended enrichments.
func TestRerank_fitsPassagesToModelLimit(t *testing.T) {
t.Parallel()
long := strings.Repeat("长", 50)
model := &limitedReranker{stubReranker: stubReranker{scores: []float64{0.9, 0.8}}, limit: 20}
res := Rerank(context.Background(), model, "q", rows(long, "short"), Options{Threshold: 0.3})
if len(model.documents) != 2 {
t.Fatalf("documents sent = %d", len(model.documents))
}
if n := len([]rune(model.documents[0])); n != 20 {
t.Fatalf("long passage has %d runes, want 20", n)
}
if model.documents[1] != "short" {
t.Fatalf("short passage changed: %q", model.documents[1])
}
if len(res.Results) != 2 {
t.Fatalf("results = %d", len(res.Results))
}
}
// An OCR chunk's body is the OCR text and its image_info repeats it.
func TestEnrichedPassage_skipsImageTextRepeatingTheBody(t *testing.T) {
t.Parallel()
r := &types.SearchResult{
Content: "Invoice total 42",
ChunkType: string(types.ChunkTypeImageOCR),
ImageInfo: `[{"url":"u","ocr_text":"Invoice total 42","caption":"a scanned invoice"}]`,
}
got := EnrichedPassage(context.Background(), r)
if strings.Count(got, "Invoice total 42") != 1 || !strings.Contains(got, "a scanned invoice") {
t.Fatalf("passage = %q", got)
}
}
// MaxCandidates sends only the best-scored rows to the model, and indices
// still point into the caller's slice.
func TestRerank_maxCandidatesKeepsBestRetrievalScores(t *testing.T) {
t.Parallel()
in := rows("a", "b", "c", "d")
for i, s := range []float64{0.2, 0.9, 0.1, 0.8} {
in[i].Score = s
}
model := &stubReranker{scores: []float64{0.7, 0.6}}
res := Rerank(context.Background(), model, "q", in, Options{Threshold: 0.3, MaxCandidates: 2})
if strings.Join(model.documents, ",") != "b,d" {
t.Fatalf("documents sent = %v, want the two best-scored rows in input order", model.documents)
}
if len(res.Indices) != 2 || res.Indices[0] != 1 || res.Indices[1] != 3 {
t.Fatalf("indices = %v, want [1 3]", res.Indices)
}
}