Raven-1/tests/test_knowledge_crops.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

351 lines
13 KiB
Python

"""The picture of where a chunk came from, and when there is not one.
Two altitudes: the cutting itself, against chunks assembled by hand so the
geometry is the thing under test, and the whole path through a manager, which
is where the lifecycle questions live -- written on index, replaced on reindex,
gone with the document.
"""
from __future__ import annotations
import io
import pytest
from raven.knowledge import _crops
from raven.knowledge._embedding import EmbeddingConfig
from raven.knowledge._manager import KnowledgeManager, chunk_ids_for
from raven.knowledge._types import Chunk, TextBlock
DIM = 8
def _page(document, pymupdf, number: int) -> None:
document.new_page()
page = document[-1]
page.insert_text(pymupdf.Point(60, 90), f"Heading on page {number}", fontsize=18)
for index in range(6):
page.insert_text(
pymupdf.Point(60, 140 + index * 26), f"Page {number} line {index} of ordinary prose.", fontsize=10
)
def _pdf(pages: int = 2) -> bytes:
import pymupdf
document = pymupdf.open()
for number in range(1, pages + 1):
_page(document, pymupdf, number)
raw = document.tobytes()
document.close()
return raw
def _chunk(metadata: dict, text: str = "some text") -> Chunk:
return Chunk(content=TextBlock(text=text), source="f.pdf", chunk_index=0, total_chunks=1, metadata=metadata)
def _box(x0=60.0, top=80.0, x1=400.0, bottom=200.0) -> dict:
return {"x0": x0, "top": top, "x1": x1, "bottom": bottom}
def _size(image: bytes) -> "tuple[int, int]":
from PIL import Image
with Image.open(io.BytesIO(image)) as opened:
assert opened.format == "WEBP"
return opened.size
# ── which regions a chunk claims ──────────────────────────────────
def test_a_merged_chunk_is_read_from_its_spans() -> None:
"""Each piece kept its own page and box when they were merged."""
chunk = _chunk(
{
"elements": [
{"char_start": 0, "char_end": 4, "page_number": 1, "bbox": _box()},
{"char_start": 5, "char_end": 9, "page_number": 2, "bbox": _box(top=300.0, bottom=400.0)},
]
}
)
assert [page for page, _ in _crops.regions_of(chunk)] == [1, 2]
def test_an_unmerged_chunk_is_read_from_its_own_fields() -> None:
"""The case that is most of a document. A chunk that merged nothing has no
spans at all -- its one page and one box are at the top level -- so reading
only the spans would leave it with no crop."""
chunk = _chunk({"page_number": 3, "bbox": _box()})
assert _crops.regions_of(chunk) == [(3, (60.0, 80.0, 400.0, 200.0))]
def test_a_chunk_that_knows_where_it_is_prefers_its_spans() -> None:
"""A merged chunk keeps a top-level page as well: the page it starts on.
Taken as the whole chunk's region it would crop the first page's box and
silently drop everything the chunk holds after it."""
chunk = _chunk(
{
"page_number": 1,
"bbox": _box(),
"elements": [
{"char_start": 0, "char_end": 4, "page_number": 1, "bbox": _box()},
{"char_start": 5, "char_end": 9, "page_number": 2, "bbox": _box()},
],
}
)
assert len(_crops.regions_of(chunk)) == 2
@pytest.mark.parametrize(
"metadata",
[
{},
{"page_number": 1},
{"bbox": _box()},
{"page_number": 1, "bbox": {"x0": 1.0, "x1": 2.0}},
],
ids=["nothing", "page without a box", "box without a page", "half a box"],
)
def test_a_chunk_with_no_position_claims_nothing(metadata) -> None:
"""A flow format knows some of a box and not the rest -- a Word paragraph
has a horizontal band and no vertical one, because that exists only once
Word has laid the text out. Half a box is not a region."""
assert _crops.regions_of(_chunk(metadata)) == []
# ── the cutting ──────────────────────────────────────────────────
def test_a_chunk_gets_an_image_of_its_own_region() -> None:
chunks = [_chunk({"page_number": 1, "bbox": _box()})]
ids = chunk_ids_for("d1", [c.text for c in chunks])
cut = _crops.crops_for(_pdf(), chunks, ids)
assert set(cut) == set(ids)
width, height = _size(cut[ids[0]])
# The box is 340x120 points at 1.5x, plus the margin on each side.
assert 500 < width < 540 and 170 < height < 210
def test_two_regions_are_stacked_into_one_image() -> None:
"""RAGFlow's shape, and the reason a merged chunk is showable at all: one
picture a chunk, however many pages it was cut from."""
one = [_chunk({"page_number": 1, "bbox": _box()})]
both = [
_chunk(
{
"elements": [
{"char_start": 0, "char_end": 4, "page_number": 1, "bbox": _box()},
{"char_start": 5, "char_end": 9, "page_number": 2, "bbox": _box()},
]
}
)
]
ids = chunk_ids_for("d1", [c.text for c in one])
document = _pdf()
single = _size(_crops.crops_for(document, one, ids)[ids[0]])
stacked = _size(_crops.crops_for(document, both, ids)[ids[0]])
assert stacked[0] == single[0], "the same width"
assert stacked[1] > single[1] * 1.9, "and both regions' height, plus the gap between them"
def test_a_chunk_with_no_position_gets_no_image() -> None:
"""Absent rather than blank. A text file's chunks have nowhere to point,
and an empty rectangle would say the page was blank, which is a different
claim."""
chunks = [_chunk({}), _chunk({"page_number": 1, "bbox": _box()}, text="other")]
ids = chunk_ids_for("d1", [c.text for c in chunks])
cut = _crops.crops_for(_pdf(), chunks, ids)
assert set(cut) == {ids[1]}
def test_a_full_page_crop_is_scaled_down_to_the_cap() -> None:
"""A chunk that swallowed a whole page must not cost twenty times what a
paragraph costs."""
chunks = [_chunk({"page_number": 1, "bbox": _box(x0=0.0, top=0.0, x1=595.0, bottom=842.0)})]
ids = chunk_ids_for("d1", [c.text for c in chunks])
width, height = _size(_crops.crops_for(_pdf(), chunks, ids)[ids[0]])
assert max(width, height) == _crops.MAX_EDGE
def test_a_region_on_a_page_that_is_not_there_is_skipped() -> None:
"""A page number out of range is a parser bug or a truncated file, and
neither is a reason to fail the whole document's crops."""
chunks = [_chunk({"page_number": 99, "bbox": _box()}), _chunk({"page_number": 1, "bbox": _box()}, text="b")]
ids = chunk_ids_for("d1", [c.text for c in chunks])
cut = _crops.crops_for(_pdf(pages=2), chunks, ids)
assert set(cut) == {ids[1]}
def test_a_chunk_missing_one_of_its_regions_gets_none_of_them() -> None:
"""Showing part of a chunk's region with nothing saying which part is worse
than showing none: a reader comparing the text to the picture would be
comparing it to the wrong half."""
chunks = [
_chunk(
{
"elements": [
{"char_start": 0, "char_end": 4, "page_number": 1, "bbox": _box()},
{"char_start": 5, "char_end": 9, "page_number": 99, "bbox": _box()},
]
}
)
]
ids = chunk_ids_for("d1", [c.text for c in chunks])
assert _crops.crops_for(_pdf(), chunks, ids) == {}
# ── through the manager ──────────────────────────────────────────
class _Stub:
model = "stub-embed"
dimensions = DIM
declared_dimensions = None
async def probe_dimensions(self) -> int:
return DIM
async def embed(self, texts: list[str]) -> list[list[float]]:
return [[0.1] * DIM for _ in texts]
@pytest.fixture
def manager(tmp_path, monkeypatch):
built = KnowledgeManager(
tmp_path / "knowledge",
embedding=EmbeddingConfig(model="stub-embed", base_url="https://x/v1", api_key="k", dimensions=DIM),
)
monkeypatch.setattr(built, "_client", lambda: _Stub())
return built
async def _indexed(manager, filename: str = "report.pdf", content: bytes | None = None):
base = await manager.create_base(name="base")
document = manager.add_document(base.id, filename=filename, content=content if content is not None else _pdf())
return base, await manager.index_document(document.id)
async def test_indexing_a_pdf_writes_a_crop_for_its_pieces(manager) -> None:
_, document = await _indexed(manager)
held, _ = await manager.document_chunks(document.id)
assert held, "the document indexed"
assert any(manager.crop_path(document.id, piece.chunk_id) for piece in held)
async def test_a_format_with_no_pages_writes_none(manager) -> None:
"""A Word file is rendered to PDF for the viewer, on demand. Converting
every upload eagerly to cut thumbnails is a conversion nobody asked for."""
_, document = await _indexed(manager, filename="notes.md", content=b"# Title\n\nSome prose about alpha.\n")
held, _ = await manager.document_chunks(document.id)
assert held
assert not any(manager.crop_path(document.id, piece.chunk_id) for piece in held)
async def test_reindexing_replaces_the_crops(manager) -> None:
"""Ids are derived from chunk text, so a document that changed leaves its
old pictures under ids nothing lists any more."""
_, document = await _indexed(manager)
before = {piece.chunk_id for piece in (await manager.document_chunks(document.id))[0]}
await manager.replace_document(document.id, filename="report.pdf", content=_pdf(pages=1))
await manager.index_document(document.id)
after = {piece.chunk_id for piece in (await manager.document_chunks(document.id))[0]}
assert before - after, "the shorter document cut differently"
assert not any(manager.crop_path(document.id, gone) for gone in before - after)
async def test_deleting_the_document_takes_its_crops(manager) -> None:
_, document = await _indexed(manager)
held, _ = await manager.document_chunks(document.id)
kept = [piece.chunk_id for piece in held if manager.crop_path(document.id, piece.chunk_id)]
assert kept
await manager.delete_document(document.id)
assert not any(manager.crop_path(document.id, chunk_id) for chunk_id in kept)
async def test_deleting_the_base_takes_them_too(manager) -> None:
base, document = await _indexed(manager)
held, _ = await manager.document_chunks(document.id)
kept = [piece.chunk_id for piece in held if manager.crop_path(document.id, piece.chunk_id)]
assert kept
await manager.delete_base(base.id)
assert not any(manager.crop_path(document.id, chunk_id) for chunk_id in kept)
async def test_a_chunk_id_is_checked_before_it_becomes_a_path(manager, tmp_path) -> None:
"""It arrives from the page, and it is about to be a path segment.
A file is planted at the traversal target so these can fail. Without one
the walk lands on nothing and `crop_path` answers None for the ordinary
reason -- which is the same answer the check gives, and so no answer at
all about whether the check is there.
"""
_, document = await _indexed(manager)
# Where `crops/<document>/../secret.webp` lands, which is the file the
# walk would serve. One directory higher and the walk misses it, and the
# case passes whether or not anything is checking.
(manager._crops / "secret.webp").write_bytes(b"planted")
for hostile in ("../../records.json", "..", "a/b", "", "x" * 65, "../secret"):
assert manager.crop_path(document.id, hostile) is None
async def test_a_document_id_is_checked_the_same_way(manager) -> None:
"""The other half of the path, and the one that was trusted.
Joining an absolute path replaces everything to its left, so a
`document` naming a directory outright served any `.webp` inside it; and
`..` walks out of the crops root while containing no separator for a
shape test to catch. Either one reaches past the state directory to
whatever the gateway's own user can read.
"""
_, document = await _indexed(manager)
outside = manager._crops.parent / "private"
outside.mkdir(parents=True, exist_ok=True)
(outside / "secret.webp").write_bytes(b"planted")
for hostile in (str(outside), "../private", "..", "a/b", "", "x" * 65):
assert manager.crop_path(hostile, "secret") is None
# And the check still leaves the feature working: a document id is uuid
# hex, which is inside the shape both halves are now held to.
held, _ = await manager.document_chunks(document.id)
assert any(manager.crop_path(document.id, piece.chunk_id) for piece in held)
async def test_a_document_whose_pages_cannot_be_read_still_indexes(manager, monkeypatch) -> None:
"""A thumbnail is worth a line in the log and nothing more."""
def explode(*args, **kwargs):
raise RuntimeError("no renderer here")
monkeypatch.setattr(_crops, "crops_for", explode)
_, document = await _indexed(manager)
assert document.status == "ready"
assert (await manager.document_chunks(document.id))[1] > 0