// Copyright 2025 The YAMS Authors // SPDX-License-Identifier: GPL-3.0-or-later #include "cross_rerank_internal.h" #include #include #include #include #include #include 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& results, const std::string& query, const SearchEngineConfig& config, std::size_t window, const CrossRerankScorerFn& reranker, const std::shared_ptr& 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 previews; std::unordered_map previewsByHash; if (metadataRepo) { std::vector 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(std::min(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 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(std::min(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 rerankTexts; rerankTexts.reserve(window); std::vector 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(maxScore - secondScore); if (!(maxScore > minScore)) { outcome.skipReason = "no_score_variance"; return outcome; } if (outcome.scoreGap < static_cast(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(maxScore - minScore); const double originalRange = origMax - origMin; const double blend = std::clamp(static_cast(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(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::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(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(rerankNorm), .source = ComponentResult::Source::Unknown, .rank = i, .snippet = results[i].snippet.empty() ? std::nullopt : std::optional(results[i].snippet), .debugInfo = {}, }); } std::stable_sort( results.begin(), results.begin() + static_cast(window), [](const SearchResult& a, const SearchResult& b) { return a.score > b.score; }); outcome.status = CrossRerankOutcome::Status::Applied; return outcome; } } // namespace yams::search::detail