Repository navigation
knowledge.search's lexical leg scores each chunk's title and section path with its text - #206
Merged
Merged
Conversation
6 tasks done
zlareb1
force-pushed
the
feat/knowledge-contextual-lexical
branch
from
November 3, 2026 15:59
dcc15aa to
f99c415
Compare
…path with its text Each chunk stores its context (document title, description and heading breadcrumb), the text its vector already embedded before the chunk. The BM25 leg counts tf and length over context and text, its token prefilter reads both text indexes, and document frequency counts a term once per chunk whichever of the two holds it (a second insert-time view into chunk_term_freq). The df rebuild, the vector rebuild under a new model and the data export carry the context too. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-contextual-lexical
branch
from
November 3, 2026 16:44
7ec43f2 to
b390b3d
Compare
6 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related: #193
Changelog category (leave one):
Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):
knowledge.search's lexical leg now scores a chunk's document title, description and section path along with its text, so a query naming a document's subject finds the sections that never repeat it. Existing documents pick this up whenloom rechunkrewrites them; then runloom lexical-stats-rebuildfor the namespace.Why
The vector leg of
knowledge.searchalready embeds each chunk as title + description + heading breadcrumb + text, but the BM25 leg scored the chunk text alone. A section whose subject lives only in the title or headings ("Refunds" in the "Lantern handbook", the resolution of runbook "E4031") was invisible to BM25, while BM25 pulled in every chunk that happened to repeat the query's words. Fused by reciprocal rank with equal weight, that noise pushed the defaulthybridmode well below its own vector leg.Measured with the fixture of #193 (21 synthetic documents, 76 answerable queries, text-embedding-3-large, one ingest per build on its own ClickHouse,
bench/knowledge_retrieval.py --namespace knowledge-retrieval-<arm> --phase search --param search_mode=<mode>):hybrid, mainhybrid, this PRlexical, mainlexical, this PRsemantic(unchanged)Cost of the lexical statement on the fixture namespace (
system.query_log, the last five lexical-arm queries of each build): main 16-18 ms, 667-671 rows, 0.93 MiB read, 7.3 MiB memory; this PR 17-19 ms, 606 rows, 1.9 MiB read, 10.3 MiB memory. It reads the context columns too and answershasAnyTokenswithout the direct-read shortcut, so bytes read about double at the same latency; a part inserted before migration 079 lackscontext_text, so the OR reads it in full;loom rechunkdoes not change that (it writes new parts and lists the old ingestion inloom.chunk_supersessions, leaving the old rows where they are), and a merged part carries neither index already. Merged parts already carry nocontent_text, so most of a large table was read in full on this leg before too; no mutation is recommended to rebuild the index.The vector leg is unchanged by construction (it embeds the same text).
hybridstill ranks belowsemanticon R@1 and MRR: equal-weight fusion and the absence of a reranker onknowledge.searchare the next changes, kept out of this one.Design
loom.chunks.context(String, default'') holds whatchunk_context(title, description, breadcrumb)returns; the vector input isembedding_text(context, text), the same string the writers embedded before, so stored vectors stay valid. Storing it (rather than rebuilding it at read time fromchunk_metadata) is what lets BM25 index it, and keeps the title, which no chunk column held.context_lc(materialized, lower-cased) with its own text indexcontext_text, kept out of merges likecontent_text(exclude_materialize_skip_indexes_on_merge = 'content_text,context_text', set at the top of the migration, before the index exists: a text index a merge cannot build fails every merge). The prefilter ishasAnyTokens(content_lc, …) OR hasAnyTokens(context_lc, …), run withquery_plan_direct_read_from_text_index = 0, as the memory, tracker and code-grep text-index legs do (answeringhasAnyTokensfrom the index alone is recorded to lose rows underORDER BY … LIMIT).EXPLAIN indexes = 1of the statement as shipped shows both skip indexes evaluated and combined by the OR (<Combined skip indexes>,Final set of granules after AND/OR processing). On one ingest of the fixture, every metric of the lexical and hybrid arms is identical with direct read on or off. Merged parts carry neither index, as forcontent_texttoday.arrayConcat(splitByNonAlpha(context_lc), splitByNonAlpha(content_lc));avgdlcounts the same words.chunk_context_term_freq_mv, writes the context's terms intoloom.chunk_term_frequnder the same chunk key.df_stateisuniqExactover(source_uri, chunk_idx), so a term in both context and text counts once. This keeps the migration additive (no view replaced).loom lexical-stats-rebuildreadsconcat(context, ' ', content).embedding_text(context, content)forchunks, exactly as this build's write path does for the chunks it writes; before, it embedded the bare text, dropping the header a rebuild should keep, and failed the page on a titled document with no text (source_text_missing, its stored vector being the title's). Only a chunk with neither text nor context stays unindexed. A chunk an older build wrote has an empty context, so its rebuilt vector loses the header it was written with (as onmain) untilloom rechunkrewrites it: rechunk before an embedding-model change.content != ''in the lexical leg), as the corpus statistics, both df views and the df rebuild already exclude it: its context alone would otherwise score against statistics that do not count it.knowledge.update_metadatawithoutreindex=trueleaves chunks alone, so both legs keep the old header until a reindex; its docstring and the knowledge page say so. Re-embedding every chunk on a title edit stays opt-in.export_knowledge) includescontext.loom rechunk's help (and the CLI snapshots and reference) and the dashboard'sreindexcomments and hint name the chunk context.chunk_metadataat read time. No title, no df for heading words, and a JSON extraction per candidate row.Scope and risk
Touches the knowledge write paths (
knowledge.add,upsert,bulk_add, andupdate_metadatawithreindex=true, which goes throughupsert), the lexical leg, its corpus statistics, the df rebuild and the chunks re-embed. Leaves fusion, the vector leg and every other plane alone. The context is document text already stored (title, description) plus headings, so erasure needs nothing new: chunks are deleted whole (loom.chunksis in the census and the purge steps). Lexical scores of documents with long descriptions shift most, since the description is part of every chunk's length.Compatibility, rollout and rollback
erasure.exportknowledge row gainscontext; nothing else changes on the wire.079_chunk_context.sqladdscontext,context_lc, thecontext_textindex (excluded from merges) andchunk_context_term_freq_mv. Additive.context(it reads'') and searchescontent_lconly; N reads both. An embedding-model rebuild that spans the deploy can have N-1 replicas embed some chunk pages from their bare text, as every build before this one did; rechunking after the deploy rewrites them.make test-mixed-versionpasses.loom rechunk --org ORG --namespace NS --applyper namespace (it re-runsknowledge.upsertfrom the stored content and re-embeds), thenloom lexical-stats-rebuild --org ORG --namespace NS, since the df views see only inserts and keep counting the superseded chunks. Rechunk before an embedding-model change on such a namespace. Without it, search behaves as before for old documents.loom lexical-stats-rebuild; N-1 scores text only, so those terms' IDF is slightly low until then.Tests
test_knowledge_chunk_rows(every writer stores the context and embeds context + text),test_knowledge_chunking(chunk_context,embedding_text),test_knowledge_lexical(SQL shape: concatenated words, both prefilters, no empty chunk, direct read off),test_bm25_shared(avgdl over both, the new view's term floor, and that both df views andlexical-stats-rebuildread the same two columns),test_erasure_export_restricted(an exported chunk carries its context, through clickhouse-local),test_provider_rebuild_batch(a chunk re-embeds its context; a titled chunk with no text rebuilds its context; a chunk with neither stays unindexed),test_insert_mv_targets,test_schema_baseline; withtest_migrations_additive,test_package_contracts,test_provider_views,test_public_copy,test_doc_links: 433 passed.test_knowledge_chunking.pygains a test that a section named only by its title is the top lexical hit and that its row stores the context; with an assertion that document frequency counts a chunk once per term whether the term is in its context or in both (uniqExactMerge(df_state)), and withtest_knowledge.py,test_knowledge_upsert.py,test_knowledge_bulk.py,test_knowledge_delete.py,test_provider_views_live_ch.py: 24 passed, 1 skipped.make format lint typecheck,pytest tests/analyzer(shapes regenerated withpython -m tests.analyzer.corpus --write: the export selectscontext),make schema-dump(diff is only this change),python -m scripts.codegen.docs_reference,make test-mixed-version: ok.AI assistance in the code (leave one; writing this description with AI is fine):
AI-generated (an agent wrote most of the diff): Claude Code; the measurement, the schema dump and the mixed-version gate were run locally.
I can explain every line of this diff and how it interacts with the rest of Loom.
Checklist
make format-check,make lint,make typecheckandmake test-unitpass; the integration suite passes if server behaviour changed.docs/reference/configuration.mdand thedocs/reference/tables (python scripts/codegen/docs_reference.py), the reach manifest,schemas/schema.sql(make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).main; no merged migration is edited.docs/describe the system as it now is, and this description names any operator steps and wire changes.tests/unit/test_public_copy.py).git commit -s), as CONTRIBUTING.md asks.🤖 Generated with Claude Code