Skip to content

knowledge.search's lexical leg scores each chunk's title and section path with its text - #206

Merged
zlareb1 merged 5 commits into
mainfrom
feat/knowledge-contextual-lexical
Nov 3, 2026
Merged

zlareb1 merged 5 commits into
mainfrom
feat/knowledge-contextual-lexical

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Related: #193

Changelog category (leave one):

  • Improvement

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 when loom rechunk rewrites them; then run loom lexical-stats-rebuild for the namespace.

Why

The vector leg of knowledge.search already 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 default hybrid mode 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>):

Arm R@1 R@5 R@10 MRR nDCG@10 context MRR identifier R@5
hybrid, main 0.526 0.776 0.895 0.629 0.610 0.546 0.857
hybrid, this PR 0.645 0.921 0.961 0.770 0.784 0.790 0.929
lexical, main 0.316 0.566 0.605 0.414 0.398 0.274 0.714
lexical, this PR 0.500 0.776 0.842 0.587 0.633 0.548 0.929
semantic (unchanged) 0.855 0.987 1.000 0.911 0.916 0.974 0.929

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 answers hasAnyTokens without the direct-read shortcut, so bytes read about double at the same latency; a part inserted before migration 079 lacks context_text, so the OR reads it in full; loom rechunk does not change that (it writes new parts and lists the old ingestion in loom.chunk_supersessions, leaving the old rows where they are), and a merged part carries neither index already. Merged parts already carry no content_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). hybrid still ranks below semantic on R@1 and MRR: equal-weight fusion and the absence of a reranker on knowledge.search are the next changes, kept out of this one.

Design

  • loom.chunks.context (String, default '') holds what chunk_context(title, description, breadcrumb) returns; the vector input is embedding_text(context, text), the same string the writers embedded before, so stored vectors stay valid. Storing it (rather than rebuilding it at read time from chunk_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 index context_text, kept out of merges like content_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 is hasAnyTokens(content_lc, …) OR hasAnyTokens(context_lc, …), run with query_plan_direct_read_from_text_index = 0, as the memory, tracker and code-grep text-index legs do (answering hasAnyTokens from the index alone is recorded to lose rows under ORDER BY … LIMIT). EXPLAIN indexes = 1 of 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 for content_text today.
  • tf and document length count arrayConcat(splitByNonAlpha(context_lc), splitByNonAlpha(content_lc)); avgdl counts the same words.
  • Document frequency: a second insert-time view, chunk_context_term_freq_mv, writes the context's terms into loom.chunk_term_freq under the same chunk key. df_state is uniqExact over (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-rebuild reads concat(context, ' ', content).
  • The provider rebuild (an embedding-model change in Settings → Models & keys) embeds embedding_text(context, content) for chunks, 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 on main) until loom rechunk rewrites it: rechunk before an embedding-model change.
  • A chunk with no text is no lexical candidate (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.
  • A first heading that repeats the title stays in the breadcrumb ("Lantern handbook\nLantern handbook > Refunds"). Dropping the repeat was measured and is worse in hybrid and semantic search (hybrid MRR 0.763 → 0.701, semantic 0.903 → 0.894): the repeat acts as a title boost.
  • knowledge.update_metadata without reindex=true leaves 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.
  • The data export (export_knowledge) includes context.
  • loom rechunk's help (and the CLI snapshots and reference) and the dashboard's reindex comments and hint name the chunk context.
  • Alternative not taken: scoring the breadcrumb from chunk_metadata at 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, and update_metadata with reindex=true, which goes through upsert), 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.chunks is 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

  • Wire: additive. Each erasure.export knowledge row gains context; nothing else changes on the wire.
  • Schema: migration 079_chunk_context.sql adds context, context_lc, the context_text index (excluded from merges) and chunk_context_term_freq_mv. Additive.
  • Rolling upgrade: N-1 inserts chunks without context (it reads '') and searches content_lc only; 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-version passes.
  • Operator steps: existing chunks have an empty context and score on their text until rewritten: loom rechunk --org ORG --namespace NS --apply per namespace (it re-runs knowledge.upsert from the stored content and re-embeds), then loom 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.
  • Rollback: revert the code; the columns, index and view stay (additive). df keeps the context terms of chunks this build wrote until loom lexical-stats-rebuild; N-1 scores text only, so those terms' IDF is slightly low until then.

Tests

  • Unit: 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 and lexical-stats-rebuild read 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; with test_migrations_additive, test_package_contracts, test_provider_views, test_public_copy, test_doc_links: 433 passed.
  • Integration against a server from source on a private ClickHouse: test_knowledge_chunking.py gains 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 with test_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 with python -m tests.analyzer.corpus --write: the export selects context), make schema-dump (diff is only this change), python -m scripts.codegen.docs_reference, make test-mixed-version: ok.
  • The fixture table above, two servers (main and this branch) on their own ClickHouse.

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 typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/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).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

zlareb1 and others added 5 commits November 3, 2026 16:43
…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]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-contextual-lexical branch from 7ec43f2 to b390b3d Compare November 3, 2026 16:44
@zlareb1
zlareb1 merged commit 84dc303 into main Nov 3, 2026
@zlareb1
zlareb1 deleted the feat/knowledge-contextual-lexical branch November 3, 2026 16:44
@zlareb1
zlareb1 restored the feat/knowledge-contextual-lexical branch November 3, 2026 16:46
@zlareb1
zlareb1 deleted the feat/knowledge-contextual-lexical branch November 3, 2026 16:46
@pufit pufit mentioned this pull request Nov 4, 2026
9 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant