Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions include/rag/index/corpus.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,19 @@ class Corpus {

[[nodiscard]] Explanation explain(std::string_view query, ChunkId id) const;

// How much lexical evidence the corpus holds for `query`: the best BM25
// score of any live chunk divided by the most this query could score
// (Bm25Index::ceiling). In [0, 1): near 0 when the corpus barely mentions
// the query, rising as one chunk covers its rarer terms. Unlike a fused or
// min-max-normalized score, the top hit is not 1 by construction, and the
// scale is the same on any corpus, so one threshold can decide whether a
// query is worth answering from this corpus at all.
struct LexicalSupport {
float support = 0.0f; // best score / ceiling
std::size_t query_terms = 0; // distinct analyzed query terms
};
[[nodiscard]] LexicalSupport lexical_support(std::string_view query) const;

// Distinct-query-term coverage for a candidate set, answered from the
// inverted index rather than by re-tokenizing each candidate's text.
// See Bm25Index::term_coverage.
Expand Down
8 changes: 8 additions & 0 deletions include/rag/lexical/bm25.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ class Bm25Index {
[[nodiscard]] std::vector<TermScore>
explain_doc(const std::vector<std::string>& q_terms, std::uint32_t doc_id) const;

// The most any document could score for `q_terms`: every distinct term at
// saturation (tf -> infinity), i.e. sum of idf(n_t) * (k1 + 1). A term no
// document contains counts at its full idf, so a query about something the
// corpus never mentions has a high ceiling no document approaches. Divided
// into a real score it gives a support ratio in [0, 1) whose scale does not
// depend on the corpus, unlike the raw score.
[[nodiscard]] float ceiling(const std::vector<std::string>& q_terms) const;

// For each doc in `docs`, how many of the DISTINCT terms in `q_terms`
// occur in it, written to `out` (same order, same size).
//
Expand Down
15 changes: 15 additions & 0 deletions src/index/corpus.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,21 @@ std::string Corpus::Explanation::summary() const {
return s;
}

Corpus::LexicalSupport Corpus::lexical_support(std::string_view query) const {
if (!bm25_.finalized()) bm25_.finalize();
LexicalSupport s;
auto terms = bm25_.tokenizer().tokenize(query);
std::sort(terms.begin(), terms.end());
terms.erase(std::unique(terms.begin(), terms.end()), terms.end());
s.query_terms = terms.size();
if (terms.empty()) return s;
const float ceiling = bm25_.ceiling(terms);
const auto top = lexical_search_locked(query, 1); // tombstones excluded
if (ceiling > 0.0f && !top.empty())
s.support = std::clamp(top.front().score.get() / ceiling, 0.0f, 1.0f);
return s;
}

Corpus::Explanation Corpus::explain(std::string_view query, ChunkId id) const {
ensure_linked();
Explanation e;
Expand Down
12 changes: 12 additions & 0 deletions src/lexical/bm25.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ float Bm25Index::idf(std::size_t n_t) const {
(static_cast<double>(n_t) + 0.5)));
}

float Bm25Index::ceiling(const std::vector<std::string>& q_terms) const {
std::vector<std::string> uniq = q_terms;
std::sort(uniq.begin(), uniq.end());
uniq.erase(std::unique(uniq.begin(), uniq.end()), uniq.end());
double sum = 0.0;
for (const auto& term : uniq) {
auto pit = postings_.find(term);
sum += idf(pit == postings_.end() ? 0 : pit->second.size());
}
return static_cast<float>(sum * (params_.k1 + 1.0f));
}

std::vector<Bm25Index::TermScore>
Bm25Index::explain_doc(const std::vector<std::string>& q_terms,
std::uint32_t doc_id) const {
Expand Down
24 changes: 24 additions & 0 deletions tests/test_main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1218,6 +1218,30 @@ TEST(explain_reconciles_with_the_search_score) {
}
}

TEST(lexical_support_is_low_for_queries_the_corpus_does_not_answer) {
rag::index::Corpus c;
REQUIRE(c.add_document("a", "Pneumonia inflames the air sacs in the lungs.").has_value());
REQUIRE(c.add_document("b", "A chest x-ray showed fluid in the lungs from pneumonia.").has_value());
REQUIRE(c.add_document("c", "Risotto is made by toasting rice and adding stock.").has_value());
REQUIRE(c.add_document("d", "The quay crane lifts forty tonnes in calm wind.").has_value());
REQUIRE(c.build().has_value());

const auto on = c.lexical_support("pneumonia fluid in the lungs");
const auto off = c.lexical_support("capital of france population");
const auto one = c.lexical_support("lungs of the french capital");
CHECK(on.query_terms >= 3);
CHECK(on.support > 0.25f && on.support < 1.0f); // never 1 by construction
CHECK(off.support == 0.0f); // no term in the corpus
CHECK(one.support > 0.0f && one.support < on.support); // one matched term of three
CHECK(c.lexical_support("").query_terms == 0);
CHECK(c.lexical_support("").support == 0.0f);

// Adding a document that answers the off-corpus query raises its support.
REQUIRE(c.add_document("e", "Paris is the capital of France; its population is two million.").has_value());
REQUIRE(c.build().has_value());
CHECK(c.lexical_support("capital of france population").support > 0.25f);
}

TEST(explain_handles_unknown_chunk_and_empty_query) {
rag::index::Corpus c;
REQUIRE(c.add_document("a", "some indexed text here").has_value());
Expand Down
Loading