Raven-1/tests/test_knowledge_lancedb.py
Kevin Hu 82c76a82a9
feat(knowledge): read every format, show what the index holds, and let an agent search it (#489)
<img width="2318" height="1448" alt="image"
src="https://github.com/user-attachments/assets/bca71d69-4972-420c-b14e-c8cf74a17de9"
/>

## Summary

Everything a knowledge base could not read, and the pieces it cut them
into
saying what they are.

**Reading a PDF.** A PDF records glyphs at coordinates; whether they are
a
heading, a table cell or a running footer is inferred from how they
look. There
are now two readers. The geometric one infers structure from type size
and
position and needs nothing but the file. The other asks deepdoc's
models, ported
into `raven/knowledge/parser/deepdoc`: a layout model that says what
each region
is, a detector and recognizer that read a page carrying no text at all,
and a
table-structure model that rebuilds a grid from a picture of one. 
 Detecting boxes around text the file already spells
out exactly costs an inference pass per page to learn less, and
recognising it
costs accuracy.

The layout graph answers with a shape its own postprocessing
raises on, and its classes are DocLayout-YOLO's order rather than the
list
Both were established by running the model, and the label order is
pinned by a test.

**Tables go in as tables.** `<table>` is the only shape that keeps what
a grid
states -- which column a cell stood under, which cells are merged, which
row is
the header -- and it is the shape a model reads a table in, which is
what these
chunks are for. PDF, Word and PowerPoint all state their merges exactly,
and
they now survive as `colspan` and `rowspan`. The flat form this replaces
had to
repeat a header standing over two columns across both of them, because
there was
nowhere to record a span; it had no callers left afterwards and is gone.
Two
deviations from upstream, both about what the string is for: every
cell's text
is escaped, where upstream interpolates it raw and a cell holding a `<`
produces
markup that is no longer a table, and the span attributes are written
only where
there is a span, where upstream emits `<td  >` for every ordinary cell.

**A picture of where each chunk came from.** A chunk is a few hundred
words with
a page number on it, which is enough to cite and not enough to answer
whether
the parser read the page correctly. So every PDF chunk that knows where
it sits
carries one image: the regions it covers, cropped out of the rendered
pages and
stacked. here they are already structured in the parser's element spans,
so
the markers would only put text nobody wrote into the thing being
embedded.
The panel draws a chunk's tables as tables, parsed and
rebuilt as elements rather than injected: a person can rewrite any piece
from
that same panel, so what comes back from the store is user input however
it got
there.

**The page that reads them.** Upstream retired the knowledge page while
this
branch was out; it is rebuilt against the new architecture, and the half
that
never existed is the one a reader needs -- what a document actually
became once
it was cut and embedded. Documents sit in one-level folders and arrive
by four
routes: a file, a folder, a URL, a written note. Adding and indexing are
two
calls on the contract and nothing drains that queue on its own, so a
page that
stopped after the first left every upload saying Queued for good.

Opening a file takes the whole page: the document on the left, the
pieces the
index holds of it on the right. The left half is the file drawn as its
own
pages rather than framed by the browser's PDF viewer, which reads where
to open
once and answers to nothing afterwards -- and which nothing can be drawn
on.
Pages are rendered once and kept, and the region a piece was cut from is
washed
over the page it came from, placed in fractions of the page so the
picture's
own scale never enters the arithmetic. Clicking a piece takes the file
there;
double-clicking opens it for rewriting.

The pieces can be searched, filtered by state, turned on and off,
deleted,
rewritten and added to, one at a time or in a batch. Every one of those
was
already on the contract with no reader for it. A base's settings are
back and
fuller: how many pieces a search returns, how documents are cut, and how
much
prose comes with a table or a figure. The embedding model is a picker
while the
base holds no pieces and a stated fact once it does -- moving it then is
the
collection made again at the new width and every document re-cut, which
is not
a thing a panel does by being saved.

**An agent can read them.** The retrieval engine was there and nothing
could
reach it: no agent had a tool that opened a library. A reader now points
a
conversation at bases from the composer, the way they pin a working
directory,
and the selection rides in the same place -- the session's metadata,
bound
around the turn.

The tool takes a query and never a base. The scope is the reader's
choice, so a
model cannot reach material nobody offered it, and it is withheld where
nothing
was picked rather than offered and refused. A hit says which document
and page
it came from, because a hit a reader cannot place is a hit they cannot
check --
and the passages are pressable in the transcript, walking into the base,
the
document, the folder it is filed under and then the piece. A citation a
reader
cannot follow is a claim they have to take on trust, and the whole point
of
searching their own material is that they can go and look.

**The word segmenter and the resources.** `raven.core.Tokenizer` is
Infinity's
`rag_tokenizer`, ported: a forward and backward maximum match over a
dictionary
trie, with stemming and lemmatisation on the latin path. XGBoost is not
carried
over. None of the data lives in git -- the dictionary, the NLTK corpora
and the
ONNX graphs run to about a hundred megabytes, so `make fetch-resources`
on an
install and an optional Docker layer behind `RAVEN_RESOURCES` both point
at one
script. A checkout that could not reach the network still works, and
every
feature that reads this data says so when asked.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Run on macOS against Python 3.12, with the deepdoc weights fetched (the
model
tests skip without them):

```
uv run pytest                        27450 passed, 111 skipped, 3 failed
npm run test --prefix ui-web          3276 passed
npm run test --prefix ui-tui          2106 passed
npm run type-check --prefix ui-web    clean (tsc)
npm run lint --prefix ui-web          clean (4 pre-existing hook warnings)
make lint-python                      clean (ruff check + format)
make lint-types                       clean (ty)
make lint-imports                     10 contracts kept, 0 broken
make check-source-language            clean
make check-large-files                clean
make build-ui                         built, both boot snapshots match
node ui-web/scripts/check-css.mjs     clean
node ui-web/scripts/check-class-namespace.mjs  clean
```

The three Python failures are not this branch's and were each confirmed
on the
base alone: one asks a host without LibreOffice to refuse a render and
this host
has LibreOffice installed, and two simulation cases fail on an
unmodified
checkout of the base commit.

The RPC contract was regenerated for both consumers and both match it
(`npm run gen --prefix ui-web`, `npm run gen:rpc --prefix ui-tui`, then
`gen:check`). The page's boot snapshots and region goldens were
refreshed where
the composer bar gained a button, and each records that button and
nothing else.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

A PDF's tables, and a Word or PowerPoint file's, are now indexed as HTML
rather
than as header-prefixed lines. Chunk text changes shape for those
documents, so
a base indexed before this and searched after it holds both forms until
its
documents are reindexed; retrieval keeps working either way, because
both forms
are text. The same applies to how much prose a table or a figure carries
with
it: the setting now reaches as far as it says, where before it stopped
at the
nearest paragraph, so a chunk cut before this keeps the narrower context
until
its document is rebuilt. Rolling back is reverting the branch and
reindexing.

The deepdoc models are optional. An install that never ran `make
fetch-resources` reads PDFs geometrically, exactly as before, and says
so when
the models are asked for by name. Nothing here reaches the network at
request
time.

Chunk crops and rendered pages are written at index time and on first
view, both
under the state directory rather than in the repository, and both are
deleted
with their document. A page is immutable for the life of its document
id, so
the route serving them caches; the document route does not. All three
routes
take ids and no path, and the two image routes answer under the
strictest
sandbox in the tree.

What an agent may search is the reader's choice and nothing else. The
tool takes
no base argument, so a model cannot name one, and it is absent from the
schema
entirely for a conversation that named none -- a lane nobody pointed at
a base
is unchanged by this branch. The bases a session carries are stored
beside its
working directory and travel no further.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-10-12 19:05:16 +08:00

458 lines
17 KiB
Python

"""Tests for the LanceDB vector store behind a knowledge base.
Against a real LanceDB on a tmp_path, not a fake: the two things most likely to
break here are the score direction and the metadata predicate, and both are
properties of the engine rather than of this code.
"""
from __future__ import annotations
import pytest
from raven.knowledge import Chunk, LanceDBVectorStore, TextBlock, VectorRecord
DIM = 4
@pytest.fixture
def store(tmp_path):
return LanceDBVectorStore(tmp_path / "vectors")
def _record(doc: str, index: int, text: str, vector: list[float], **metadata) -> VectorRecord:
return VectorRecord(
vector=vector,
document_id=doc,
chunk=Chunk(
content=TextBlock(text=text),
source=f"{doc}.md",
chunk_index=index,
total_chunks=1,
metadata=metadata,
),
)
async def _seed(store: LanceDBVectorStore, name: str = "kb") -> None:
await store.create_collection(name, DIM)
await store.insert(
name,
[
_record("d1", 0, "hello", [1.0, 0.0, 0.0, 0.0], lang="zh"),
_record("d2", 0, "goodbye", [0.0, 1.0, 0.0, 0.0], lang="en"),
_record("d2", 1, "farewell", [0.0, 0.9, 0.1, 0.0], lang="en"),
],
)
async def test_create_is_idempotent_and_has_collection_agrees(store) -> None:
assert await store.has_collection("kb") is False
await store.create_collection("kb", DIM)
await store.create_collection("kb", DIM)
assert await store.has_collection("kb") is True
async def test_delete_collection_is_forgiving_of_a_missing_one(store) -> None:
await store.delete_collection("never-made")
await store.create_collection("kb", DIM)
await store.delete_collection("kb")
assert await store.has_collection("kb") is False
async def test_inserting_nothing_is_not_an_error(store) -> None:
await store.create_collection("kb", DIM)
await store.insert("kb", [])
assert await store.list_documents("kb") == []
async def test_search_returns_similarity_highest_first(store) -> None:
"""The interface promises similarity, LanceDB reports cosine distance. An
unconverted score would sort the least relevant chunk to the top and put a
relevance floor on the wrong side of every comparison."""
await _seed(store)
hits = await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=3)
assert [h.document_id for h in hits][0] == "d1"
assert hits == sorted(hits, key=lambda h: h.score, reverse=True)
assert hits[0].score == pytest.approx(1.0, abs=1e-5)
assert hits[0].score > hits[-1].score
async def test_search_round_trips_the_whole_chunk(store) -> None:
await _seed(store)
hit = (await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=1))[0]
assert hit.chunk.text == "hello"
assert hit.chunk.source == "d1.md"
assert hit.chunk.metadata == {"lang": "zh"}
async def test_metadata_filter_narrows_before_ranking(store) -> None:
"""Filtering after ranking would return one row here, not two: the nearest
chunk is the excluded one, so a top-2 taken first and filtered second comes
back short."""
await _seed(store)
hits = await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=2, metadata_filter={"lang": "en"})
assert len(hits) == 2
assert {h.document_id for h in hits} == {"d2"}
async def test_metadata_filter_ands_its_keys(store) -> None:
await store.create_collection("kb", DIM)
await store.insert(
"kb",
[
_record("a", 0, "both", [1.0, 0.0, 0.0, 0.0], lang="en", kind="note"),
_record("b", 0, "one", [1.0, 0.0, 0.0, 0.0], lang="en", kind="page"),
],
)
hits = await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=5, metadata_filter={"lang": "en", "kind": "note"})
assert [h.document_id for h in hits] == ["a"]
async def test_a_value_of_a_different_type_does_not_match(store) -> None:
"""JSON-encoding the value keeps 1 and "1" apart. Flattening with str()
would let a filter for the number match the string."""
await store.create_collection("kb", DIM)
await store.insert("kb", [_record("a", 0, "x", [1.0, 0.0, 0.0, 0.0], page=1)])
assert await store.search("kb", [1.0, 0.0, 0.0, 0.0], metadata_filter={"page": "1"}) == []
assert len(await store.search("kb", [1.0, 0.0, 0.0, 0.0], metadata_filter={"page": 1})) == 1
async def test_a_quote_in_a_metadata_value_does_not_break_the_predicate(store) -> None:
"""The predicate is SQL, and the values are user data."""
await store.create_collection("kb", DIM)
await store.insert("kb", [_record("a", 0, "x", [1.0, 0.0, 0.0, 0.0], note="it's fine")])
hits = await store.search("kb", [1.0, 0.0, 0.0, 0.0], metadata_filter={"note": "it's fine"})
assert [h.document_id for h in hits] == ["a"]
async def test_delete_removes_one_document_and_leaves_the_rest(store) -> None:
await _seed(store)
await store.delete("kb", "d2")
assert {d.document_id for d in await store.list_documents("kb")} == {"d1"}
assert {h.document_id for h in await store.search("kb", [0.0, 1.0, 0.0, 0.0], top_k=5)} == {"d1"}
async def test_list_documents_counts_chunks_per_document(store) -> None:
await _seed(store)
summaries = {d.document_id: d for d in await store.list_documents("kb")}
assert summaries["d1"].chunk_count == 1
assert summaries["d2"].chunk_count == 2
assert summaries["d2"].source == "d2.md"
assert summaries["d1"].metadata == {"lang": "zh"}
async def test_list_documents_honours_the_metadata_filter(store) -> None:
await _seed(store)
summaries = await store.list_documents("kb", metadata_filter={"lang": "zh"})
assert [d.document_id for d in summaries] == ["d1"]
async def test_two_collections_do_not_see_each_other(store) -> None:
await _seed(store, "kb")
await store.create_collection("other", DIM)
await store.insert("other", [_record("z", 0, "elsewhere", [1.0, 0.0, 0.0, 0.0])])
assert {d.document_id for d in await store.list_documents("other")} == {"z"}
assert "z" not in {d.document_id for d in await store.list_documents("kb")}
async def test_the_directory_is_not_created_until_it_is_used(tmp_path) -> None:
"""Building the store is a wiring step; a deployment that never opens a
knowledge base should not find one on disk."""
path = tmp_path / "vectors"
LanceDBVectorStore(path)
assert not path.exists()
await LanceDBVectorStore(path).create_collection("kb", DIM)
assert path.exists()
async def test_collection_names_pages_to_the_end(tmp_path) -> None:
"""``list_tables`` is paginated. Reading only the first response makes an
existing collection look missing once a deployment outgrows one page --
which reports an indexed base as absent and silently skips dropping it."""
class _Response:
def __init__(self, tables, page_token):
self.tables = tables
self.page_token = page_token
class _FakeDB:
def __init__(self):
self.tokens_seen = []
async def list_tables(self, page_token=None):
self.tokens_seen.append(page_token)
if page_token is None:
return _Response(["kb-a", "kb-b"], "next")
return _Response(["kb-c"], None)
store = LanceDBVectorStore(tmp_path / "vectors")
store._db = _FakeDB()
assert await store.has_collection("kb-c") is True
assert store._db.tokens_seen == [None, "next"]
# ---------------------------------------------------------------------------
# a collection an earlier build wrote
# ---------------------------------------------------------------------------
async def _pre_upgrade(store: LanceDBVectorStore, name: str = "kb") -> None:
"""A collection in the shape a build before the chunk columns wrote it.
Made through LanceDB rather than through the store, because the store no
longer knows how to write this shape -- which is the point: what has to
keep working is the collection already on an installed machine.
"""
import pyarrow as pa
db = await store._connect()
schema = pa.schema(
[
pa.field("vector", pa.list_(pa.float32(), DIM)),
pa.field("document_id", pa.string()),
pa.field("source", pa.string()),
pa.field("chunk_index", pa.int32()),
pa.field("chunk_json", pa.string()),
pa.field("metadata_kv", pa.list_(pa.string())),
]
)
table = await db.create_table(name, schema=schema)
await table.add(
[
{
"vector": [1.0, 0.0, 0.0, 0.0],
"document_id": "d1",
"source": "d1.md",
"chunk_index": 0,
"chunk_json": Chunk(
content=TextBlock(text="the older rows"),
source="d1.md",
chunk_index=0,
total_chunks=1,
).model_dump_json(),
"metadata_kv": [],
}
]
)
async def test_a_collection_from_an_earlier_build_can_still_be_searched(store) -> None:
"""The filter names `enabled`, and a collection written before that column
existed has no such field -- the scan does not read it as null, it refuses
the query outright. A base indexed before this build was unsearchable until
something happened to write to it."""
await _pre_upgrade(store)
hits = await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=5)
assert [hit.chunk.text for hit in hits] == ["the older rows"]
async def test_its_rows_come_back_enabled_and_unnamed(store) -> None:
"""Enabled by construction: there was no way to turn one off when they were
written. Unnamed because nothing addressed a single piece back then, and a
reader who wants to act on one reindexes the document."""
await _pre_upgrade(store)
hit = (await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=5))[0]
assert hit.chunk_id == ""
async def test_searching_one_widens_it_once_and_for_all(store) -> None:
"""A metadata edit rather than a rewrite, so it is cheap to do on the read
that needs it -- and having been done, every later path finds the columns
already there."""
await _pre_upgrade(store)
await store.search("kb", [1.0, 0.0, 0.0, 0.0], top_k=5)
table = await store._table("kb")
assert {"chunk_id", "enabled", "manual", "text"} <= set((await table.schema()).names)
async def test_a_keyword_search_of_one_answers_nothing_rather_than_failing(store) -> None:
"""The other half of retrieval, and the one the widening cannot rescue.
The text column is what BM25 tokenizes, and a row written before it existed
has nothing in it -- widening gives the column, not the words. So an older
base answers by meaning and not by keyword until its documents are
reindexed, which writes the text. Answering nothing is the honest outcome;
what matters is that it does not refuse the query."""
await _pre_upgrade(store)
assert await store.keyword_search("kb", "older", top_k=5) == []
await store.insert("kb", [_record("d2", 0, "the newer rows", [0.0, 1.0, 0.0, 0.0])])
hits = await store.keyword_search("kb", "newer", top_k=5)
assert [hit.chunk.text for hit in hits] == ["the newer rows"]
# -- renumbering after a hand edit ---------------------------------
def _numbered(doc: str, index: int, total: int, **kw) -> VectorRecord:
"""One piece that can be addressed by id, as indexing writes them."""
return VectorRecord(
vector=[1.0 if n == index % DIM else 0.0 for n in range(DIM)],
document_id=doc,
chunk_id=f"c{index:04d}",
chunk=Chunk(
content=TextBlock(text=f"piece {index}"),
source=f"{doc}.md",
chunk_index=index,
total_chunks=total,
metadata={"lang": "en"},
),
**kw,
)
async def _version(store, name: str = "kb") -> int:
return await (await store._writable(name)).version()
async def test_renumbering_a_document_is_one_write(store) -> None:
"""Deleting the first piece changes the index of every piece after it and
the total on all of them. A write per row is a commit per row: measured on
a 400-chunk document, one deletion took the table from version 2 to 402
and 9.9 MB on disk, with the panel's controls inert for the whole time.
"""
await store.create_collection("kb", DIM)
await store.insert("kb", [_numbered("d1", n, 40) for n in range(40)])
await store.delete_chunks("kb", ["c0000"], document_id="d1")
before = await _version(store)
total = await store.renumber("kb", "d1")
assert total == 39
assert await _version(store) == before + 1, "one commit, however many rows moved"
async def test_renumbering_leaves_the_numbers_contiguous(store) -> None:
await store.create_collection("kb", DIM)
await store.insert("kb", [_numbered("d1", n, 5) for n in range(5)])
await store.delete_chunks("kb", ["c0002"], document_id="d1")
total = await store.renumber("kb", "d1")
held, _ = await store.list_chunks("kb", "d1")
assert [piece.chunk.chunk_index for piece in held] == list(range(total))
assert {piece.chunk.total_chunks for piece in held} == {total}
async def test_renumbering_keeps_every_column_it_did_not_rewrite(store) -> None:
"""The rows go back through a merge that replaces what it matches, so a
column left out of the read is a column emptied on disk. The vector is the
one that would not be noticed: the rows still list, and the base simply
stops answering."""
await store.create_collection("kb", DIM)
await store.insert(
"kb",
[
_numbered("d1", 0, 4),
_numbered("d1", 1, 4, enabled=False),
_numbered("d1", 2, 4, manual=True),
_numbered("d1", 3, 4),
],
)
await store.delete_chunks("kb", ["c0000"], document_id="d1")
await store.renumber("kb", "d1")
held, _ = await store.list_chunks("kb", "d1")
assert [piece.enabled for piece in held] == [False, True, True]
assert [piece.manual for piece in held] == [False, True, False]
assert all(piece.chunk.metadata == {"lang": "en"} for piece in held)
hits = await store.search("kb", [0.0, 0.0, 1.0, 0.0], top_k=1)
assert hits and hits[0].chunk.text == "piece 2", "the vectors still answer"
async def test_renumbering_a_document_already_in_order_writes_nothing(store) -> None:
await store.create_collection("kb", DIM)
await store.insert("kb", [_numbered("d1", n, 3) for n in range(3)])
before = await _version(store)
assert await store.renumber("kb", "d1") == 3
assert await _version(store) == before, "nothing moved, so nothing was written"
async def test_rows_from_before_ids_existed_are_left_alone(store) -> None:
"""They carry an empty id, which names no row. The per-row path spent a
commit on each of them that changed nothing."""
await store.create_collection("kb", DIM)
await store.insert(
"kb",
[
VectorRecord(
vector=[1.0, 0.0, 0.0, 0.0],
document_id="d1",
chunk=Chunk(content=TextBlock(text="old"), source="d1.md", chunk_index=7, total_chunks=9),
)
],
)
before = await _version(store)
assert await store.renumber("kb", "d1") == 1
assert await _version(store) == before, "nothing addressable, so nothing written"
async def test_renumbering_an_absent_collection_answers_nothing(store) -> None:
assert await store.renumber("nosuchbase", "d1") == 0
async def test_renumbering_one_document_does_not_touch_an_identical_row_in_another(store) -> None:
"""A chunk id is derived from the text, so two documents in one base that
hold the same sentence hold the same id.
Keyed on the id alone, the merge matches the other document's row and
overwrites it with this one's -- which is that document silently losing a
piece. Caught here with the id shared on purpose; the per-row path it
replaces scoped by the document for the same reason.
"""
shared = "the same sentence in both"
await store.create_collection("kb", DIM)
await store.insert(
"kb",
[
VectorRecord(
vector=[1.0, 0.0, 0.0, 0.0],
document_id="d1",
chunk_id="shared",
chunk=Chunk(content=TextBlock(text=shared), source="d1.md", chunk_index=0, total_chunks=3),
),
_numbered("d1", 1, 3),
_numbered("d1", 2, 3),
],
)
await store.insert(
"kb",
[
VectorRecord(
vector=[1.0, 0.0, 0.0, 0.0],
document_id="d2",
chunk_id="shared",
chunk=Chunk(content=TextBlock(text=shared), source="d2.md", chunk_index=0, total_chunks=2),
),
_numbered("d2", 1, 2),
],
)
await store.delete_chunks("kb", ["c0001"], document_id="d1")
await store.renumber("kb", "d1")
other, count = await store.list_chunks("kb", "d2")
assert count == 2, "the other document kept both its pieces"
assert [piece.chunk.source for piece in other] == ["d2.md", "d2.md"], "and they are still its own"
assert [piece.chunk.total_chunks for piece in other] == [2, 2]