From d278570f9ba0fadd825e28e1b14eb3001091861b Mon Sep 17 00:00:00 2001 From: sail3r <82087684+sail3r@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:10:00 +1300 Subject: [PATCH 1/4] contextual: a title from front matter, and nothing the chunk already holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The extractive context took a document's first line as its title and prepended it to every chunk. On real corpora that went wrong three ways: - Front matter. A page that opens with YAML front matter got the title "---", and its best sentence could be a front-matter line ("--- — title: Harbour Pilot Manual"). Every page of a docs site built with front matter was affected. - One-line documents. The title is the whole document, so the chunk was sent with its own text prepended: every memory fact in an agentty history (213 of 213 passages) reached the model twice. - First chunks. The heading is both the title and inside the chunk, so it was repeated; and a later chunk could get the heading line ("# Title") as its best sentence, after the title itself. The title is now front matter's `title:` when present, else the first non-empty line after the front matter. Front matter is not a source of sentences. The title is left out when the chunk contains it, and a heading that is the title is not a candidate sentence: the rule the best sentence already followed. --- include/rag/text/contextual.hpp | 6 ++- src/text/contextual.cpp | 81 +++++++++++++++++++++++++++++---- tests/test_main.cpp | 34 ++++++++++++++ 3 files changed, 110 insertions(+), 11 deletions(-) diff --git a/include/rag/text/contextual.hpp b/include/rag/text/contextual.hpp index f0be3ae..719ec51 100644 --- a/include/rag/text/contextual.hpp +++ b/include/rag/text/contextual.hpp @@ -35,8 +35,10 @@ using Contextualizer = void contextualize(std::vector& chunks, std::string_view document, const Contextualizer& ctx = {}); -// The deterministic default: document title (first non-empty line) + the -// document sentence with the highest term overlap with the chunk. +// The deterministic default: the document's title + the document sentence with +// the highest term overlap with the chunk. The title is front matter's +// `title:` when present, else the first non-empty line after any front +// matter. Neither is repeated when the chunk already contains it. [[nodiscard]] std::string extractive_context(std::string_view document, std::string_view chunk); diff --git a/src/text/contextual.cpp b/src/text/contextual.cpp index 8687021..40974e5 100644 --- a/src/text/contextual.cpp +++ b/src/text/contextual.cpp @@ -32,12 +32,68 @@ std::vector doc_sentences(std::string_view s) { return out; } -std::string_view first_line(std::string_view s) { - auto nl = s.find('\n'); - auto line = nl == std::string_view::npos ? s : s.substr(0, nl); - // strip markdown heading marks - while (!line.empty() && (line.front() == '#' || line.front() == ' ')) line.remove_prefix(1); - return line; +// A leading YAML front-matter block ("---" ... "---"): its body and the +// document after it. Absent: empty body, the whole document as the rest. +struct FrontMatter { + std::string_view yaml; + std::string_view rest; +}; +FrontMatter split_front_matter(std::string_view s) { + auto line_end = [&](std::size_t at) { + auto nl = s.find('\n', at); + return nl == std::string_view::npos ? s.size() : nl; + }; + auto is_fence = [](std::string_view l) { + while (!l.empty() && (l.back() == '\r' || l.back() == ' ')) l.remove_suffix(1); + return l == "---"; + }; + if (!is_fence(s.substr(0, line_end(0)))) return {{}, s}; + std::size_t at = line_end(0) + 1; + while (at < s.size()) { + const std::size_t e = line_end(at); + if (is_fence(s.substr(at, e - at))) + return {s.substr(line_end(0) + 1, at - line_end(0) - 1), + e < s.size() ? s.substr(e + 1) : std::string_view{}}; + at = e + 1; + } + return {{}, s}; // unclosed: not front matter +} + +std::string_view trim(std::string_view v) { + while (!v.empty() && std::isspace((unsigned char)v.front())) v.remove_prefix(1); + while (!v.empty() && std::isspace((unsigned char)v.back())) v.remove_suffix(1); + return v; +} + +// The `title:` value of a front-matter block, unquoted; empty when absent. +std::string_view yaml_title(std::string_view yaml) { + while (!yaml.empty()) { + auto nl = yaml.find('\n'); + auto line = yaml.substr(0, nl); + yaml = nl == std::string_view::npos ? std::string_view{} : yaml.substr(nl + 1); + if (!line.starts_with("title:")) continue; + auto v = trim(line.substr(6)); + if (v.size() >= 2 && (v.front() == '"' || v.front() == '\'') && v.back() == v.front()) + v = v.substr(1, v.size() - 2); + return v; + } + return {}; +} + +// The document's title: front matter's `title:` when it has one, else the +// first non-empty line after any front matter, without heading marks. +std::string_view doc_title(std::string_view document) { + const auto fm = split_front_matter(document); + if (auto t = yaml_title(fm.yaml); !t.empty()) return t; + std::string_view s = fm.rest; + while (!s.empty()) { + auto nl = s.find('\n'); + auto line = trim(s.substr(0, nl)); + s = nl == std::string_view::npos ? std::string_view{} : s.substr(nl + 1); + while (!line.empty() && (line.front() == '#' || line.front() == ' ')) line.remove_prefix(1); + if (!line.empty()) return line; + } + return {}; } } // namespace @@ -60,8 +116,9 @@ struct PreparedDoc { PreparedDoc prepare(const Tokenizer& tok, std::string_view document) { PreparedDoc p; - p.title = std::string(first_line(document)); - p.sentences = doc_sentences(document); + p.title = std::string(doc_title(document)); + // Front matter is metadata (keys and values), not prose to quote. + p.sentences = doc_sentences(split_front_matter(document).rest); p.sent_tokens.reserve(p.sentences.size()); for (auto s : p.sentences) p.sent_tokens.push_back(tok.tokenize(s)); return p; @@ -77,11 +134,17 @@ std::string situate(const Tokenizer& tok, const PreparedDoc& p, std::string_view // Skip a sentence the chunk already contains: repeating the chunk back // to itself situates nothing. if (chunk.find(p.sentences[i]) != std::string_view::npos) continue; + // Nor the title again, as its heading line ("# Title"). + auto s = p.sentences[i]; + while (!s.empty() && (s.front() == '#' || s.front() == ' ')) s.remove_prefix(1); + if (!p.title.empty() && s == p.title) continue; std::size_t ov = 0; for (const auto& t : p.sent_tokens[i]) if (cset.count(t)) ++ov; if (ov > best_overlap) { best_overlap = ov; best = p.sentences[i]; } } - std::string out = p.title; + // Same rule for the title: a chunk that holds it (the first chunk, or a + // one-line document) gains nothing from it but a repeat. + std::string out = chunk.find(p.title) == std::string_view::npos ? p.title : std::string{}; if (!best.empty()) { if (!out.empty()) out += " — "; out += std::string(best); } return out; } diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 2de12f8..9528ca9 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -3078,6 +3078,40 @@ TEST(contextualize_adds_situating_context) { CHECK(chunks[0].context.find("Acme") != std::string::npos); } +// Front matter is metadata: its fence is not a title, its `title:` is. +TEST(extractive_context_reads_the_title_from_front_matter) { + const std::string doc = + "---\ntitle: Harbour Pilot Manual\ndescription: Boarding rules.\n---\n\n" + "# Harbour Pilot Manual\n\nThe pilot boards at the outer buoy.\n\n" + "Boarding is refused when the swell exceeds 2.5 metres.\n"; + const auto ctx = rag::text::extractive_context( + doc, "Boarding is refused when the swell exceeds 2.5 metres."); + CHECK(ctx.starts_with("Harbour Pilot Manual")); + CHECK(ctx.find("# Harbour") == std::string::npos); // the heading is not quoted back + CHECK(ctx.find("---") == std::string::npos); + CHECK(ctx.find("description:") == std::string::npos); + + // No `title:` key: the first non-empty line after the front matter. + const std::string untitled = "---\nnav_order: 3\n---\n\n# Lighthouse\n\nThe lamp is lit at dusk.\n"; + CHECK(rag::text::extractive_context(untitled, "The lamp is lit at dusk.") + .starts_with("Lighthouse")); +} + +// A chunk that already holds the title or the best sentence gets neither +// again: the whole of a one-line document, or a document's first chunk. +TEST(extractive_context_does_not_repeat_what_the_chunk_holds) { + const std::string line = "The quay crane lifts at most 40 tonnes in calm wind."; + CHECK(rag::text::extractive_context(line, line).empty()); + + const std::string doc = "# Tide Table Notes\n\nHigh water at the inner basin is 40 minutes late.\n"; + CHECK(rag::text::extractive_context(doc, doc).empty()); + + // A later chunk still gets the title it lacks. + const std::string two = "# Tide Table Notes\n\nHigh water is late.\n\nNeap tides raise the basin by 2.9 metres.\n"; + CHECK(rag::text::extractive_context(two, "Neap tides raise the basin by 2.9 metres.") + .starts_with("Tide Table Notes")); +} + // ── Cascade ──────────────────────────────────────────────── TEST(cascade_narrows_through_stages) { From b340a5c6facd96bb29eb373158a2dc752468631f Mon Sep 17 00:00:00 2001 From: sail3r <82087684+sail3r@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:38:30 +1300 Subject: [PATCH 2/4] build: no warnings outside the library A full build (tests, examples, bench) printed 39 -Wunused-result warnings under GCC 16, whose libstdc++ marks std::expected [[nodiscard]]. Compiling the same files with the library's own -Wall -Wextra -Wpedantic shows four more (three -Wcomment, one -Wunused-variable) that the default build hides, because only the ragcpp target gets those flags. CI's -Werror lane covers only ragcpp too, so none of them failed a build. - Examples check every add() and build() through a small must() that prints the error and exits. They are what users copy, so they should not show failures being dropped. - ragcpp_rcp_tests gets -Wno-unused-result (/wd4834 on MSVC), the same fixture idiom ragcpp_tests already has. - The two benches cast their setup results to void. - include/rag/rcp/convert.hpp: an unused `double b`. - Three usage comments ended a line in a backslash, which continued the comment onto the next line; each command is now on one line. --- bench/batch_bench.cpp | 6 ++-- bench/bench.cpp | 2 +- bench/code_retrieval_bench.cpp | 3 +- examples/advanced.cpp | 13 +++++-- examples/full_pipeline.cpp | 27 ++++++++++----- examples/graphrag.cpp | 31 +++++++++++------ examples/plugin_backend/host_demo.cpp | 15 ++++++-- .../plugin_backend/local_embedder_plugin.cpp | 3 +- examples/plugin_backend/local_host_demo.cpp | 17 +++++++--- .../plugin_backend/my_embedder_plugin.cpp | 3 +- examples/polyglot/python_backend.cpp | 15 ++++++-- examples/quickstart.cpp | 21 ++++++++---- examples/rcp_server.cpp | 34 ++++++++++++------- include/rag/rcp/convert.hpp | 2 +- tests/CMakeLists.txt | 7 ++++ 15 files changed, 137 insertions(+), 62 deletions(-) diff --git a/bench/batch_bench.cpp b/bench/batch_bench.cpp index 49a79b3..508504c 100644 --- a/bench/batch_bench.cpp +++ b/bench/batch_bench.cpp @@ -41,9 +41,9 @@ int main() { auto emb = rag::plugin::make_embedder(nlohmann::json{{"type", "hash"}, {"dim", 384}}); c.set_embedder(std::move(*emb)); for (std::size_t i = 0; i < docs; ++i) - c.add_document("d" + std::to_string(i), - "retrieval document " + std::to_string(i) + - " about vectors graphs indexes ranking and search"); + (void)c.add_document("d" + std::to_string(i), + "retrieval document " + std::to_string(i) + + " about vectors graphs indexes ranking and search"); (void)c.build(); std::vector qs; diff --git a/bench/bench.cpp b/bench/bench.cpp index 15650ae..e774c5e 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -40,7 +40,7 @@ int main(int argc, char** argv) { auto t0 = Clock::now(); for (std::size_t i = 0; i < n; ++i) - engine.add("doc" + std::to_string(i), synth_doc(rng, 60)); + (void)engine.add("doc" + std::to_string(i), synth_doc(rng, 60)); auto t1 = Clock::now(); auto b = engine.build(); auto t2 = Clock::now(); diff --git a/bench/code_retrieval_bench.cpp b/bench/code_retrieval_bench.cpp index c236efc..dc189ce 100644 --- a/bench/code_retrieval_bench.cpp +++ b/bench/code_retrieval_bench.cpp @@ -26,8 +26,7 @@ // chunks. That isolates chunking, which is the claim. // // Usage: -// ragcpp_code_retrieval_bench \ -// --model=model.onnx --tokenizer=tokenizer.json [--limit=N] +// ragcpp_code_retrieval_bench --model=model.onnx --tokenizer=tokenizer.json [--limit=N] // // Requires -DRAGCPP_WITH_ONNX=ON (otherwise there is no embedder and nothing to // measure). diff --git a/examples/advanced.cpp b/examples/advanced.cpp index 51b5d43..0e76b35 100644 --- a/examples/advanced.cpp +++ b/examples/advanced.cpp @@ -8,8 +8,17 @@ // build/examples/ragcpp_advanced #include +#include #include +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} + int main() { rag::Engine engine; const char* docs[] = { @@ -28,8 +37,8 @@ int main() { "Risotto: toast arborio rice, then add warm stock gradually while " "stirring until creamy; finish with butter and parmesan.", }; - for (int i = 0; i < 7; ++i) engine.add("d" + std::to_string(i), docs[i]); - engine.build(); + for (int i = 0; i < 7; ++i) must(engine.add("d" + std::to_string(i), docs[i]), "add"); + must(engine.build(), "build"); const char* Q = "how does approximate nearest neighbour vector search work"; std::printf("Query: %s\n\n", Q); diff --git a/examples/full_pipeline.cpp b/examples/full_pipeline.cpp index 6b439e0..1f74958 100644 --- a/examples/full_pipeline.cpp +++ b/examples/full_pipeline.cpp @@ -5,8 +5,17 @@ // parent-document stitching, persistence, and reload. #include +#include #include +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} + int main() { using namespace rag; @@ -16,22 +25,22 @@ int main() { Engine engine(cfg); engine.with_embedder(dense::AnyEmbedder{dense::HashEmbedder{256}}); - engine.add("ann.md", + must(engine.add("ann.md", "# Approximate Nearest Neighbours\n\nHNSW builds a layered proximity graph " "for logarithmic-time vector search. Binary quantization speeds the walk.", - {{"section","index"}}); - engine.add("bm25.md", + {{"section","index"}}), "add"); + must(engine.add("bm25.md", "# Lexical Retrieval\n\nBM25 scores documents by term frequency and inverse " "document frequency, catching exact keyword matches embeddings miss.", - {{"section","lexical"}}); - engine.add("fusion.md", + {{"section","lexical"}}), "add"); + must(engine.add("fusion.md", "# Fusion\n\nReciprocal rank fusion combines lexical and dense rankings " "without score normalization, the most robust hybrid retrieval method.", - {{"section","fusion"}}); - engine.add("risotto.md", + {{"section","fusion"}}), "add"); + must(engine.add("risotto.md", "# Risotto\n\nToast arborio rice, then add warm stock one ladle at a time.", - {{"section","cooking"}}); - engine.build(); + {{"section","cooking"}}), "add"); + must(engine.build(), "build"); // A local cross-encoder stand-in: reward passages sharing query terms. rerank::ScoreFnReranker ce([](std::string_view q, std::string_view p) { diff --git a/examples/graphrag.cpp b/examples/graphrag.cpp index 6189239..8c8b9bb 100644 --- a/examples/graphrag.cpp +++ b/examples/graphrag.cpp @@ -8,30 +8,39 @@ // build/examples/ragcpp_graphrag #include +#include #include +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} + int main() { rag::Engine engine; // A small corpus where documents LINK to one another (markdown) and cluster // by topic. No embedder → similarity edges fall back to lexical Jaccard and // retrieval degrades gracefully to BM25. Attach an embedder for dense edges. - engine.add("intro.md", + must(engine.add("intro.md", "Retrieval-augmented generation grounds a language model on external " - "documents. See [dense](dense.md) and [graph](graph.md) for the engine internals."); - engine.add("dense.md", + "documents. See [dense](dense.md) and [graph](graph.md) for the engine internals."), "add"); + must(engine.add("dense.md", "The dense retriever embeds passages and ranks them by cosine similarity " - "over an HNSW index. It pairs with [lexical](lexical.md) BM25 scoring."); - engine.add("lexical.md", + "over an HNSW index. It pairs with [lexical](lexical.md) BM25 scoring."), "add"); + must(engine.add("lexical.md", "BM25 is the Okapi lexical ranker: term frequency saturation plus inverse " - "document frequency. It fuses with dense results via reciprocal rank fusion."); - engine.add("graph.md", + "document frequency. It fuses with dense results via reciprocal rank fusion."), "add"); + must(engine.add("graph.md", "GraphRAG builds a document graph — link edges and similarity edges — then " - "detects communities and summarizes each cluster for corpus-level questions."); - engine.add("cooking.md", + "detects communities and summarizes each cluster for corpus-level questions."), "add"); + must(engine.add("cooking.md", "Risotto: toast arborio rice, then ladle warm stock gradually while stirring " - "until creamy. Finish with butter and parmesan off the heat."); - engine.build(); + "until creamy. Finish with butter and parmesan off the heat."), "add"); + must(engine.build(), "build"); // ── Document graph ───────────────────────────────────────────────────────── auto g = engine.graph(); diff --git a/examples/plugin_backend/host_demo.cpp b/examples/plugin_backend/host_demo.cpp index 6a112f7..4f4824b 100644 --- a/examples/plugin_backend/host_demo.cpp +++ b/examples/plugin_backend/host_demo.cpp @@ -8,6 +8,15 @@ #include #include +#include + +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} int main(int argc, char** argv) { // Path to the compiled plugin (defaults to the CMake output location). @@ -45,9 +54,9 @@ int main(int argc, char** argv) { return 1; } - engine.add("d1", "The Eiffel Tower is in Paris."); - engine.add("d2", "Photosynthesis happens in plant leaves."); - engine.build(); + must(engine.add("d1", "The Eiffel Tower is in Paris."), "add"); + must(engine.add("d2", "Photosynthesis happens in plant leaves."), "add"); + must(engine.build(), "build"); auto hits = engine.search("landmark in Paris", 2); if (hits) { diff --git a/examples/plugin_backend/local_embedder_plugin.cpp b/examples/plugin_backend/local_embedder_plugin.cpp index 8cd1cd4..b40c4b1 100644 --- a/examples/plugin_backend/local_embedder_plugin.cpp +++ b/examples/plugin_backend/local_embedder_plugin.cpp @@ -14,8 +14,7 @@ // of the host and no host knowledge that this type exists. // // Build (standalone, MUST match the host toolchain and rag headers/ABI): -// g++-15 -std=c++23 -fPIC -shared -I/include \ -// local_embedder_plugin.cpp -o liblocal_ngram.so +// g++-15 -std=c++23 -fPIC -shared -I/include local_embedder_plugin.cpp -o liblocal_ngram.so // Or via this repo's CMake (target: local_ngram_plugin). #include diff --git a/examples/plugin_backend/local_host_demo.cpp b/examples/plugin_backend/local_host_demo.cpp index 8ceaebf..07d74c9 100644 --- a/examples/plugin_backend/local_host_demo.cpp +++ b/examples/plugin_backend/local_host_demo.cpp @@ -15,6 +15,15 @@ #include #include +#include + +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} namespace { void print_names(const rag::plugin::Registries& regs) { @@ -71,10 +80,10 @@ int main(int argc, char** argv) { } std::printf("\nWired embedder from config (onnx || retry(local_ngram)).\n"); - engine.add("d1", "The Eiffel Tower is a landmark in Paris."); - engine.add("d2", "Photosynthesis converts light into chemical energy in leaves."); - engine.add("d3", "HNSW is a graph index for approximate nearest neighbours."); - engine.build(); + must(engine.add("d1", "The Eiffel Tower is a landmark in Paris."), "add"); + must(engine.add("d2", "Photosynthesis converts light into chemical energy in leaves."), "add"); + must(engine.add("d3", "HNSW is a graph index for approximate nearest neighbours."), "add"); + must(engine.build(), "build"); // Character n-grams give sub-word recall: "landmarks near Paris" matches d1 // even though the exact phrase never appears. diff --git a/examples/plugin_backend/my_embedder_plugin.cpp b/examples/plugin_backend/my_embedder_plugin.cpp index 0f8a0e4..76d76aa 100644 --- a/examples/plugin_backend/my_embedder_plugin.cpp +++ b/examples/plugin_backend/my_embedder_plugin.cpp @@ -6,8 +6,7 @@ // no recompile of the host application. // // Build (standalone, matching the host toolchain): -// g++-15 -std=c++23 -fPIC -shared -I/include \ -// my_embedder_plugin.cpp -o libreverse_hash.so +// g++-15 -std=c++23 -fPIC -shared -I/include my_embedder_plugin.cpp -o libreverse_hash.so // Or via this repo's CMake (see CMakeLists.txt here). #include diff --git a/examples/polyglot/python_backend.cpp b/examples/polyglot/python_backend.cpp index 8663bcf..5788ba7 100644 --- a/examples/polyglot/python_backend.cpp +++ b/examples/polyglot/python_backend.cpp @@ -15,6 +15,15 @@ #include #include +#include + +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} int main(int argc, char** argv) { std::string server = argc > 1 ? argv[1] : "examples/polyglot/ragcpp_server.py"; @@ -38,9 +47,9 @@ int main(int argc, char** argv) { return 1; } - engine.add("a", "The Eiffel Tower is in Paris."); - engine.add("b", "Plants perform photosynthesis in their leaves."); - engine.build(); + must(engine.add("a", "The Eiffel Tower is in Paris."), "add"); + must(engine.add("b", "Plants perform photosynthesis in their leaves."), "add"); + must(engine.build(), "build"); if (auto hits = engine.search("landmark in the French capital", 2)) { std::printf("[embedder-via-python] top = %s (%zu hits)\n", hits->empty() ? "(none)" : (*hits)[0].uri.c_str(), hits->size()); diff --git a/examples/quickstart.cpp b/examples/quickstart.cpp index 6ff3fb6..8bf55eb 100644 --- a/examples/quickstart.cpp +++ b/examples/quickstart.cpp @@ -1,20 +1,29 @@ // examples/quickstart.cpp — the smallest useful rag-cpp program. #include +#include #include +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} + int main() { rag::Engine engine; engine.with_embedder(rag::dense::AnyEmbedder{rag::dense::HashEmbedder{256}}); - engine.add("intro.md", + must(engine.add("intro.md", "# rag-cpp\n\nrag-cpp is a type-theoretic retrieval engine. It fuses BM25 " - "lexical scoring with dense vector search using reciprocal rank fusion."); - engine.add("hnsw.md", + "lexical scoring with dense vector search using reciprocal rank fusion."), "add"); + must(engine.add("hnsw.md", "# ANN\n\nThe HNSW index gives logarithmic-time nearest-neighbour search " - "over embeddings, with binary quantization and Matryoshka truncation."); - engine.add("unrelated.md", - "# Cooking\n\nTo make a good risotto, toast the rice before adding stock."); + "over embeddings, with binary quantization and Matryoshka truncation."), "add"); + must(engine.add("unrelated.md", + "# Cooking\n\nTo make a good risotto, toast the rice before adding stock."), "add"); if (auto b = engine.build(); !b) { std::printf("build failed: %s\n", b.error().message.c_str()); diff --git a/examples/rcp_server.cpp b/examples/rcp_server.cpp index 187bc91..538e721 100644 --- a/examples/rcp_server.cpp +++ b/examples/rcp_server.cpp @@ -32,25 +32,33 @@ namespace { +// An example must not swallow a failure: report it and stop. +void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} + // A small, self-contained demo corpus so the server answers real queries out of // the box (and the conformance checker has something to retrieve). rag::Engine build_demo_engine() { rag::Engine engine; engine.with_embedder(rag::dense::AnyEmbedder{rag::dense::HashEmbedder{256}}); - engine.add("doc://eiffel", "The Eiffel Tower is a wrought-iron lattice tower on " - "the Champ de Mars in Paris, France, completed in 1889.", - {{"lang", "en"}, {"topic", "landmarks"}}); - engine.add("doc://photosynthesis", "Photosynthesis is the process by which plants " - "convert light energy into chemical energy stored in glucose.", - {{"lang", "en"}, {"topic", "biology"}}); - engine.add("doc://hnsw", "HNSW is a graph index for approximate nearest-neighbour " - "search, giving logarithmic query time over high-dimensional vectors.", - {{"lang", "en"}, {"topic", "retrieval"}}); - engine.add("doc://rrf", "Reciprocal rank fusion merges ranked lists from lexical " - "and dense retrievers into one robust hybrid ranking.", - {{"lang", "en"}, {"topic", "retrieval"}}); - engine.build(); + must(engine.add("doc://eiffel", "The Eiffel Tower is a wrought-iron lattice tower on " + "the Champ de Mars in Paris, France, completed in 1889.", + {{"lang", "en"}, {"topic", "landmarks"}}), "add"); + must(engine.add("doc://photosynthesis", "Photosynthesis is the process by which plants " + "convert light energy into chemical energy stored in glucose.", + {{"lang", "en"}, {"topic", "biology"}}), "add"); + must(engine.add("doc://hnsw", "HNSW is a graph index for approximate nearest-neighbour " + "search, giving logarithmic query time over high-dimensional vectors.", + {{"lang", "en"}, {"topic", "retrieval"}}), "add"); + must(engine.add("doc://rrf", "Reciprocal rank fusion merges ranked lists from lexical " + "and dense retrievers into one robust hybrid ranking.", + {{"lang", "en"}, {"topic", "retrieval"}}), "add"); + must(engine.build(), "build"); return engine; } diff --git a/include/rag/rcp/convert.hpp b/include/rag/rcp/convert.hpp index 34a86a2..27ec8dc 100644 --- a/include/rag/rcp/convert.hpp +++ b/include/rag/rcp/convert.hpp @@ -242,7 +242,7 @@ compile_filter(const Json& raw, const Json& advertised_fields) { catch (...) { return false; } }; auto cmp = [&](auto pred) -> bool { - double a, b; + double a; if (num(mv, a) && val.is_number()) return pred(a, val.get()); return pred(std::string_view(mv), std::string_view(as_str(val))); }; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index af4ef5e..2670a59 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,4 +20,11 @@ if(TARGET ragcpp::rcp) add_executable(ragcpp_rcp_tests test_rcp.cpp) target_link_libraries(ragcpp_rcp_tests PRIVATE ragcpp::rcp) add_test(NAME ragcpp_rcp_tests COMMAND ragcpp_rcp_tests) + # Same fixture idiom as ragcpp_tests: setup discards Results, the + # assertions check what is retrieved afterwards. + if(MSVC) + target_compile_options(ragcpp_rcp_tests PRIVATE /wd4834) + else() + target_compile_options(ragcpp_rcp_tests PRIVATE -Wno-unused-result) + endif() endif() From 36923f29dbf3fc2c5608361f20fa30f67c30847d Mon Sep 17 00:00:00 2001 From: sail3r <82087684+sail3r@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:51:27 +1300 Subject: [PATCH 3/4] contextual: more front-matter shapes; a title is held only by its own line Review follow-ups to the front-matter title: - The title check was a substring match, so a chunk that only mentioned a short title ("see Usage above") lost its title context. A chunk now holds the title only when one of its lines is the title: its heading, its front-matter key, or the whole of a one-line document. - Front matter: a UTF-8 byte-order mark before the fence, TOML front matter (+++, title = "..."), and a YAML block title (title: >) taking its first line instead of ">". - A setext underline (=== or ---) is heading markup, never a best sentence; the setext heading text is the title, as before. Tests cover each shape, a quoted title with a colon, an unclosed fence, the mid-sentence mention and a setext heading. --- src/text/contextual.cpp | 106 ++++++++++++++++++++++++++++++---------- tests/test_main.cpp | 29 +++++++++++ 2 files changed, 109 insertions(+), 26 deletions(-) diff --git a/src/text/contextual.cpp b/src/text/contextual.cpp index 40974e5..26943e2 100644 --- a/src/text/contextual.cpp +++ b/src/text/contextual.cpp @@ -32,31 +32,35 @@ std::vector doc_sentences(std::string_view s) { return out; } -// A leading YAML front-matter block ("---" ... "---"): its body and the -// document after it. Absent: empty body, the whole document as the rest. +// A leading front-matter block, YAML ("---" fences) or TOML ("+++"): its +// body, its fence, and the document after it. Absent: empty body and fence, +// the whole document (minus a UTF-8 BOM) as the rest. struct FrontMatter { - std::string_view yaml; + std::string_view body; + std::string_view fence; std::string_view rest; }; FrontMatter split_front_matter(std::string_view s) { + if (s.starts_with("\xEF\xBB\xBF")) s.remove_prefix(3); auto line_end = [&](std::size_t at) { auto nl = s.find('\n', at); return nl == std::string_view::npos ? s.size() : nl; }; - auto is_fence = [](std::string_view l) { + auto bare = [](std::string_view l) { while (!l.empty() && (l.back() == '\r' || l.back() == ' ')) l.remove_suffix(1); - return l == "---"; + return l; }; - if (!is_fence(s.substr(0, line_end(0)))) return {{}, s}; + const auto open = bare(s.substr(0, line_end(0))); + if (open != "---" && open != "+++") return {{}, {}, s}; std::size_t at = line_end(0) + 1; while (at < s.size()) { const std::size_t e = line_end(at); - if (is_fence(s.substr(at, e - at))) - return {s.substr(line_end(0) + 1, at - line_end(0) - 1), + if (bare(s.substr(at, e - at)) == open) + return {s.substr(line_end(0) + 1, at - line_end(0) - 1), open, e < s.size() ? s.substr(e + 1) : std::string_view{}}; at = e + 1; } - return {{}, s}; // unclosed: not front matter + return {{}, {}, s}; // unclosed: not front matter } std::string_view trim(std::string_view v) { @@ -65,14 +69,29 @@ std::string_view trim(std::string_view v) { return v; } -// The `title:` value of a front-matter block, unquoted; empty when absent. -std::string_view yaml_title(std::string_view yaml) { - while (!yaml.empty()) { - auto nl = yaml.find('\n'); - auto line = yaml.substr(0, nl); - yaml = nl == std::string_view::npos ? std::string_view{} : yaml.substr(nl + 1); - if (!line.starts_with("title:")) continue; - auto v = trim(line.substr(6)); +// The title value of a front-matter block, unquoted: YAML `title: x` (a +// folded or literal block `title: >` takes its first indented line) or TOML +// `title = "x"`. Empty when absent. +std::string_view fm_title(const FrontMatter& fm) { + std::string_view body = fm.body; + const char sep = fm.fence == "+++" ? '=' : ':'; + bool block = false; + while (!body.empty()) { + auto nl = body.find('\n'); + auto line = body.substr(0, nl); + body = nl == std::string_view::npos ? std::string_view{} : body.substr(nl + 1); + if (block) { + if (line.empty() || !std::isspace((unsigned char)line.front())) return {}; + return trim(line); + } + if (!line.starts_with("title")) continue; + auto after = trim(line.substr(5)); + if (after.empty() || after.front() != sep) continue; + auto v = trim(after.substr(1)); + if (sep == ':' && !v.empty() && (v.front() == '>' || v.front() == '|')) { + block = true; + continue; + } if (v.size() >= 2 && (v.front() == '"' || v.front() == '\'') && v.back() == v.front()) v = v.substr(1, v.size() - 2); return v; @@ -80,11 +99,47 @@ std::string_view yaml_title(std::string_view yaml) { return {}; } -// The document's title: front matter's `title:` when it has one, else the +// A line as a title would read in it: trimmed, without ATX heading marks or a +// front-matter `title` key. +std::string_view title_form(std::string_view line) { + line = trim(line); + while (!line.empty() && (line.front() == '#' || line.front() == ' ')) line.remove_prefix(1); + if (line.starts_with("title")) { + auto after = trim(line.substr(5)); + if (!after.empty() && (after.front() == ':' || after.front() == '=')) { + line = trim(after.substr(1)); + if (line.size() >= 2 && (line.front() == '"' || line.front() == '\'') + && line.back() == line.front()) + line = line.substr(1, line.size() - 2); + } + } + return line; +} + +// Whether some line of `chunk` is the title itself, so prepending it repeats +// the chunk. A title merely mentioned mid-sentence is not held. +bool holds_title(std::string_view chunk, std::string_view title) { + if (title.empty()) return true; + while (!chunk.empty()) { + auto nl = chunk.find('\n'); + if (title_form(chunk.substr(0, nl)) == title) return true; + chunk = nl == std::string_view::npos ? std::string_view{} : chunk.substr(nl + 1); + } + return false; +} + +// A setext underline ("=====" or "-----"): heading markup, not a sentence. +bool is_underline(std::string_view s) { + s = trim(s); + return !s.empty() && (s.find_first_not_of('=') == std::string_view::npos + || s.find_first_not_of('-') == std::string_view::npos); +} + +// The document's title: front matter's title when it has one, else the // first non-empty line after any front matter, without heading marks. std::string_view doc_title(std::string_view document) { const auto fm = split_front_matter(document); - if (auto t = yaml_title(fm.yaml); !t.empty()) return t; + if (auto t = fm_title(fm); !t.empty()) return t; std::string_view s = fm.rest; while (!s.empty()) { auto nl = s.find('\n'); @@ -134,17 +189,16 @@ std::string situate(const Tokenizer& tok, const PreparedDoc& p, std::string_view // Skip a sentence the chunk already contains: repeating the chunk back // to itself situates nothing. if (chunk.find(p.sentences[i]) != std::string_view::npos) continue; - // Nor the title again, as its heading line ("# Title"). - auto s = p.sentences[i]; - while (!s.empty() && (s.front() == '#' || s.front() == ' ')) s.remove_prefix(1); - if (!p.title.empty() && s == p.title) continue; + // Nor the title again as its heading ("# Title"), nor a setext underline. + if (title_form(p.sentences[i]) == p.title || is_underline(p.sentences[i])) continue; std::size_t ov = 0; for (const auto& t : p.sent_tokens[i]) if (cset.count(t)) ++ov; if (ov > best_overlap) { best_overlap = ov; best = p.sentences[i]; } } - // Same rule for the title: a chunk that holds it (the first chunk, or a - // one-line document) gains nothing from it but a repeat. - std::string out = chunk.find(p.title) == std::string_view::npos ? p.title : std::string{}; + // Same rule for the title: a chunk with a line that IS the title (its + // heading, its front-matter key, or the whole of a one-line document) + // gains nothing from it but a repeat. + std::string out = holds_title(chunk, p.title) ? std::string{} : p.title; if (!best.empty()) { if (!out.empty()) out += " — "; out += std::string(best); } return out; } diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 9528ca9..ed9d92f 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -3095,6 +3095,24 @@ TEST(extractive_context_reads_the_title_from_front_matter) { const std::string untitled = "---\nnav_order: 3\n---\n\n# Lighthouse\n\nThe lamp is lit at dusk.\n"; CHECK(rag::text::extractive_context(untitled, "The lamp is lit at dusk.") .starts_with("Lighthouse")); + + const auto title_of = [](const std::string& d) { + return rag::text::extractive_context(d, "An unrelated later line."); + }; + // Quoted, with a colon inside the value. + CHECK(title_of("---\ntitle: \"Pilots: Boarding\"\n---\nBody text here.\n") + .starts_with("Pilots: Boarding")); + // A folded block title takes its first line. + CHECK(title_of("---\ntitle: >\n Long Harbour Title\n---\nBody text here.\n") + .starts_with("Long Harbour Title")); + // TOML front matter (Hugo). + CHECK(title_of("+++\ntitle = \"Tide Notes\"\n+++\nBody text here.\n") + .starts_with("Tide Notes")); + // A UTF-8 byte-order mark before the fence. + CHECK(title_of("\xEF\xBB\xBF---\ntitle: Crane Rules\n---\nBody text here.\n") + .starts_with("Crane Rules")); + // An unclosed fence is not front matter: the first line is the title. + CHECK(title_of("---\nnot closed\nBody text here.\n").starts_with("---")); } // A chunk that already holds the title or the best sentence gets neither @@ -3110,6 +3128,17 @@ TEST(extractive_context_does_not_repeat_what_the_chunk_holds) { const std::string two = "# Tide Table Notes\n\nHigh water is late.\n\nNeap tides raise the basin by 2.9 metres.\n"; CHECK(rag::text::extractive_context(two, "Neap tides raise the basin by 2.9 metres.") .starts_with("Tide Table Notes")); + + // A chunk that only mentions the title mid-sentence still gets it. + const std::string usage = "# Usage\n\nRun it once.\n\nSee Usage above for the flags.\n"; + CHECK(rag::text::extractive_context(usage, "See Usage above for the flags.") + .starts_with("Usage")); + + // Setext headings: the title is the text line, the underline is never quoted. + const std::string setext = "Harbour Rules\n=============\n\nShips moor at berth 4.\n\nTugs wait at the buoy.\n"; + const auto sctx = rag::text::extractive_context(setext, "Tugs wait at the buoy."); + CHECK(sctx.starts_with("Harbour Rules")); + CHECK(sctx.find("===") == std::string::npos); } // ── Cascade ──────────────────────────────────────────────── From fe3c44fa4dbd9029e04391aa3133002891ab74a2 Mon Sep 17 00:00:00 2001 From: sail3r <82087684+sail3r@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:51:27 +1300 Subject: [PATCH 4/4] examples: one shared must(); keep the usage comment readable Each example carried its own copy of must(). They now include examples/must.hpp, and the include blocks are back as they were plus that one line. The code_retrieval_bench usage comment is split across two lines again, without the backslash that made -Wcomment fire. --- bench/code_retrieval_bench.cpp | 4 +++- examples/advanced.cpp | 10 +--------- examples/full_pipeline.cpp | 10 +--------- examples/graphrag.cpp | 10 +--------- examples/must.hpp | 13 +++++++++++++ examples/plugin_backend/host_demo.cpp | 10 +--------- examples/plugin_backend/local_host_demo.cpp | 10 +--------- examples/polyglot/python_backend.cpp | 10 +--------- examples/quickstart.cpp | 10 +--------- examples/rcp_server.cpp | 9 +-------- 10 files changed, 24 insertions(+), 72 deletions(-) create mode 100644 examples/must.hpp diff --git a/bench/code_retrieval_bench.cpp b/bench/code_retrieval_bench.cpp index dc189ce..43afeaa 100644 --- a/bench/code_retrieval_bench.cpp +++ b/bench/code_retrieval_bench.cpp @@ -26,7 +26,9 @@ // chunks. That isolates chunking, which is the claim. // // Usage: -// ragcpp_code_retrieval_bench --model=model.onnx --tokenizer=tokenizer.json [--limit=N] +// ragcpp_code_retrieval_bench +// --model=model.onnx --tokenizer=tokenizer.json [--limit=N] +// (one command; shown on two lines) // // Requires -DRAGCPP_WITH_ONNX=ON (otherwise there is no embedder and nothing to // measure). diff --git a/examples/advanced.cpp b/examples/advanced.cpp index 0e76b35..49af475 100644 --- a/examples/advanced.cpp +++ b/examples/advanced.cpp @@ -8,16 +8,8 @@ // build/examples/ragcpp_advanced #include -#include #include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "must.hpp" int main() { rag::Engine engine; diff --git a/examples/full_pipeline.cpp b/examples/full_pipeline.cpp index 1f74958..26c25be 100644 --- a/examples/full_pipeline.cpp +++ b/examples/full_pipeline.cpp @@ -5,16 +5,8 @@ // parent-document stitching, persistence, and reload. #include -#include #include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "must.hpp" int main() { using namespace rag; diff --git a/examples/graphrag.cpp b/examples/graphrag.cpp index 8c8b9bb..ed56436 100644 --- a/examples/graphrag.cpp +++ b/examples/graphrag.cpp @@ -8,16 +8,8 @@ // build/examples/ragcpp_graphrag #include -#include #include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "must.hpp" int main() { rag::Engine engine; diff --git a/examples/must.hpp b/examples/must.hpp new file mode 100644 index 0000000..3b68cd4 --- /dev/null +++ b/examples/must.hpp @@ -0,0 +1,13 @@ +#pragma once +// examples/must.hpp - one helper every example uses: an example must not +// swallow a failure, so it reports it and stops. + +#include +#include + +inline void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} diff --git a/examples/plugin_backend/host_demo.cpp b/examples/plugin_backend/host_demo.cpp index 4f4824b..89f4097 100644 --- a/examples/plugin_backend/host_demo.cpp +++ b/examples/plugin_backend/host_demo.cpp @@ -8,15 +8,7 @@ #include #include -#include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "../must.hpp" int main(int argc, char** argv) { // Path to the compiled plugin (defaults to the CMake output location). diff --git a/examples/plugin_backend/local_host_demo.cpp b/examples/plugin_backend/local_host_demo.cpp index 07d74c9..1bae6b3 100644 --- a/examples/plugin_backend/local_host_demo.cpp +++ b/examples/plugin_backend/local_host_demo.cpp @@ -15,15 +15,7 @@ #include #include -#include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "../must.hpp" namespace { void print_names(const rag::plugin::Registries& regs) { diff --git a/examples/polyglot/python_backend.cpp b/examples/polyglot/python_backend.cpp index 5788ba7..d15cde2 100644 --- a/examples/polyglot/python_backend.cpp +++ b/examples/polyglot/python_backend.cpp @@ -15,15 +15,7 @@ #include #include -#include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "../must.hpp" int main(int argc, char** argv) { std::string server = argc > 1 ? argv[1] : "examples/polyglot/ragcpp_server.py"; diff --git a/examples/quickstart.cpp b/examples/quickstart.cpp index 8bf55eb..d44f821 100644 --- a/examples/quickstart.cpp +++ b/examples/quickstart.cpp @@ -1,16 +1,8 @@ // examples/quickstart.cpp — the smallest useful rag-cpp program. #include -#include #include - -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} +#include "must.hpp" int main() { rag::Engine engine; diff --git a/examples/rcp_server.cpp b/examples/rcp_server.cpp index 538e721..dc59c01 100644 --- a/examples/rcp_server.cpp +++ b/examples/rcp_server.cpp @@ -29,17 +29,10 @@ #include #include #include +#include "must.hpp" namespace { -// An example must not swallow a failure: report it and stop. -void must(const auto& result, const char* what) { - if (!result) { - std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); - std::exit(1); - } -} - // A small, self-contained demo corpus so the server answers real queries out of // the box (and the conformance checker has something to retrieve). rag::Engine build_demo_engine() {