yams/src/search/cross_rerank.cpp
trvon 9019539427
fix(search): fetch cross-rerank content by hash for hits without an id
Simeon-lexical and vector hits reach the cross rerank with document.id 0,
and content previews were fetched only for id > 0. About 12% of window
documents (those without a snippet that already fills the text budget)
were scored on the file name alone. Resolve their previews by hash.

Bench: neutral (held-out nDCG@10 -0.0006 [-0.0015, +0.0001], test
+0.0003). The cross rerank itself stays on: switching it off on top of
the lexical rerank costs -0.0039 [-0.0078, -0.0001] held-out.

Signed-off-by: trvon <me@trevon.dev>
2026-10-30 08:53:55 -06:00

241 lines
9.8 KiB
C++

// Copyright 2025 The YAMS Authors
// SPDX-License-Identifier: GPL-3.0-or-later
#include "cross_rerank_internal.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <limits>
#include <string_view>
#include <unordered_map>
namespace yams::search::detail {
namespace {
void appendRerankTextPart(std::string& out, const std::string& part) {
if (part.empty()) {
return;
}
if (!out.empty()) {
out.push_back('\n');
}
out += part;
}
} // namespace
std::string buildCrossRerankText(const SearchResult& result, std::string_view contentPreview,
std::size_t textLimit) {
std::string text;
// The directory path is left out: it is shared noise across candidates and took about half
// of a 256-char budget on the retrieval bench. Engine results may carry only filePath.
if (!result.document.fileName.empty()) {
appendRerankTextPart(text, result.document.fileName);
} else {
const auto& path = result.document.filePath;
const auto slash = path.find_last_of("/\\");
appendRerankTextPart(text, slash == std::string::npos ? path : path.substr(slash + 1));
}
appendRerankTextPart(text, result.snippet);
if (!contentPreview.empty() && text.size() < textLimit) {
const size_t remaining = textLimit > text.size() ? textLimit - text.size() : size_t{0};
appendRerankTextPart(text, std::string(contentPreview.substr(0, remaining)));
}
if (text.size() > textLimit) {
text.resize(textLimit);
}
return text;
}
CrossRerankOutcome
applyCrossRerank(std::vector<SearchResult>& results, const std::string& query,
const SearchEngineConfig& config, std::size_t window,
const CrossRerankScorerFn& reranker,
const std::shared_ptr<metadata::MetadataRepository>& metadataRepo) {
CrossRerankOutcome outcome;
outcome.window = window;
outcome.replaceScores = config.rerankReplaceScores;
if (window == 0) {
outcome.skipReason = "no_candidates";
return outcome;
}
if (!reranker) {
outcome.skipReason = "reranker_unavailable";
return outcome;
}
const size_t textLimit = config.rerankSnippetMaxChars;
// One bounded preview query for the whole window; the previous per-result getContent()
// read every document's full text only to keep its first textLimit characters.
std::unordered_map<int64_t, std::string> previews;
std::unordered_map<std::string, std::string> previewsByHash;
if (metadataRepo) {
std::vector<int64_t> ids;
ids.reserve(window);
for (size_t i = 0; i < window; ++i) {
if (results[i].document.id > 0 && textLimit > 0 &&
buildCrossRerankText(results[i], {}, textLimit).size() < textLimit) {
ids.push_back(results[i].document.id);
}
}
if (!ids.empty()) {
auto fetched = metadataRepo->batchGetContentPreview(
ids, static_cast<int>(std::min<std::size_t>(textLimit, INT_MAX)));
if (!fetched) {
outcome.status = CrossRerankOutcome::Status::Failed;
outcome.errorMessage = fetched.error().message;
return outcome;
}
previews = std::move(fetched.value());
}
// Hits without a metadata id (Simeon-lexical, vector) are resolved by hash.
std::vector<std::string> hashes;
for (size_t i = 0; i < window; ++i) {
if (results[i].document.id <= 0 && !results[i].document.sha256Hash.empty() &&
textLimit > 0 &&
buildCrossRerankText(results[i], {}, textLimit).size() < textLimit) {
hashes.push_back(results[i].document.sha256Hash);
}
}
if (!hashes.empty()) {
auto fetched = metadataRepo->batchGetDocumentsWithContentPreview(
hashes, static_cast<int>(std::min<std::size_t>(textLimit, INT_MAX)));
if (!fetched) {
outcome.status = CrossRerankOutcome::Status::Failed;
outcome.errorMessage = fetched.error().message;
return outcome;
}
for (auto& [hash, docAndPreview] : fetched.value()) {
previewsByHash.emplace(hash, std::move(docAndPreview.second));
}
}
}
std::vector<std::string> rerankTexts;
rerankTexts.reserve(window);
std::vector<double> originalScores;
originalScores.reserve(window);
for (size_t i = 0; i < window; ++i) {
std::string_view preview;
if (const auto it = previews.find(results[i].document.id); it != previews.end()) {
preview = it->second;
} else if (const auto hit = previewsByHash.find(results[i].document.sha256Hash);
hit != previewsByHash.end()) {
preview = hit->second;
}
rerankTexts.push_back(buildCrossRerankText(results[i], preview, textLimit));
originalScores.push_back(results[i].score);
}
outcome.attempted = true;
auto scoreResult = reranker(query, rerankTexts);
if (!scoreResult) {
outcome.errorMessage = scoreResult.error().message;
if (scoreResult.error().code == ErrorCode::NotImplemented ||
scoreResult.error().code == ErrorCode::NotInitialized) {
outcome.skipReason = "reranker_unavailable";
} else {
outcome.status = CrossRerankOutcome::Status::Failed;
}
return outcome;
}
const auto& scores = scoreResult.value();
if (scores.size() != window) {
outcome.status = CrossRerankOutcome::Status::Failed;
outcome.errorMessage = "score_size_mismatch";
return outcome;
}
auto [minIt, maxIt] = std::minmax_element(scores.begin(), scores.end());
const float minScore = minIt != scores.end() && std::isfinite(*minIt) ? *minIt : 0.0F;
const float maxScore = maxIt != scores.end() && std::isfinite(*maxIt) ? *maxIt : 0.0F;
// Runner-up starts at minScore, not 0: scores may all be negative.
float secondScore = minScore;
for (float score : scores) {
if (!std::isfinite(score) || score >= maxScore) {
continue;
}
secondScore = std::max(secondScore, score);
}
outcome.scoreGap = static_cast<double>(maxScore - secondScore);
if (!(maxScore > minScore)) {
outcome.skipReason = "no_score_variance";
return outcome;
}
if (outcome.scoreGap < static_cast<double>(std::max(0.0F, config.rerankScoreGapThreshold))) {
outcome.skipReason = "score_gap_below_threshold";
return outcome;
}
auto [origMinIt, origMaxIt] = std::minmax_element(originalScores.begin(), originalScores.end());
const double origMin = origMinIt != originalScores.end() ? *origMinIt : 0.0;
const double origMax = origMaxIt != originalScores.end() ? *origMaxIt : 0.0;
const double rerankRange = static_cast<double>(maxScore - minScore);
const double originalRange = origMax - origMin;
const double blend = std::clamp(static_cast<double>(config.rerankBlendWeight), 0.0, 1.0);
outcome.blendWeight = blend;
// Map the normalized window score back onto the window's original score range, kept strictly
// above every tail score for later raw-score sorts. Lexical tie-breaking can still reorder
// results within its configured epsilon bucket.
double mappedLow = origMin;
if (results.size() > window) {
const double tailMax =
std::max_element(
results.begin() + static_cast<std::ptrdiff_t>(window), results.end(),
[](const SearchResult& a, const SearchResult& b) { return a.score < b.score; })
->score;
if (tailMax >= mappedLow) {
mappedLow = std::nextafter(tailMax, std::numeric_limits<double>::infinity());
}
}
// No usable original spread (flat window, or the tail reaches it): use a unit span.
const double mappedSpan = origMax > mappedLow ? origMax - mappedLow : 1.0;
outcome.components.reserve(window);
outcome.docTraces.reserve(window);
for (size_t i = 0; i < window; ++i) {
const double rerankNorm =
std::clamp((static_cast<double>(scores[i]) - minScore) / rerankRange, 0.0, 1.0);
const double originalNorm =
originalRange > 0.0
? std::clamp((originalScores[i] - origMin) / originalRange, 0.0, 1.0)
: 1.0;
const double finalNorm = config.rerankReplaceScores
? rerankNorm
: blend * rerankNorm + (1.0 - blend) * originalNorm;
const double finalScore = mappedLow + finalNorm * mappedSpan;
outcome.docTraces.push_back(CrossRerankDocTrace{
.filePath = results[i].document.filePath,
.documentHash = results[i].document.sha256Hash,
.originalScore = originalScores[i],
.rerankScore = scores[i],
.rerankNorm = rerankNorm,
.finalScore = finalScore,
});
results[i].score = finalScore;
outcome.components.push_back(ComponentResult{
.documentHash = results[i].document.sha256Hash,
.filePath = results[i].document.filePath,
.score = static_cast<float>(rerankNorm),
.source = ComponentResult::Source::Unknown,
.rank = i,
.snippet = results[i].snippet.empty() ? std::nullopt
: std::optional<std::string>(results[i].snippet),
.debugInfo = {},
});
}
std::stable_sort(
results.begin(), results.begin() + static_cast<std::ptrdiff_t>(window),
[](const SearchResult& a, const SearchResult& b) { return a.score > b.score; });
outcome.status = CrossRerankOutcome::Status::Applied;
return outcome;
}
} // namespace yams::search::detail