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

553 lines
21 KiB
Python

"""Tests for the knowledge registry: what survives a restart, and what a
delete takes with it."""
from __future__ import annotations
import json
import pytest
from raven.knowledge._records import (
DEFAULT_CHUNK_OVERLAP,
DEFAULT_CHUNK_SIZE,
DEFAULT_SEPARATOR,
DEFAULT_TOP_K,
RecordStore,
)
@pytest.fixture
def store(tmp_path):
return RecordStore(tmp_path / "knowledge" / "records.json")
def _base(store: RecordStore, name: str = "notes"):
return store.create_base(name=name, embedding_model="text-embedding-3-small", dimensions=1536)
def test_a_base_round_trips_through_disk(tmp_path) -> None:
path = tmp_path / "knowledge" / "records.json"
created = _base(RecordStore(path))
reopened = RecordStore(path).get_base(created.id)
assert reopened == created
assert reopened.dimensions == 1536
def test_the_registry_directory_is_made_on_first_write(tmp_path) -> None:
path = tmp_path / "knowledge" / "records.json"
assert not path.parent.exists()
_base(RecordStore(path))
assert path.exists()
def test_an_unreadable_registry_starts_empty_instead_of_raising(tmp_path) -> None:
"""A half-written file is what a full disk leaves behind. Refusing to open
would take the whole gateway down over a list of names."""
path = tmp_path / "records.json"
path.write_text("{not json", encoding="utf-8")
store = RecordStore(path)
assert store.list_bases() == []
def test_a_malformed_entry_is_dropped_and_the_rest_load(tmp_path) -> None:
path = tmp_path / "records.json"
good = _base(RecordStore(path))
raw = json.loads(path.read_text(encoding="utf-8"))
raw["bases"]["broken"] = {"name": "no other fields"}
path.write_text(json.dumps(raw), encoding="utf-8")
assert [b.id for b in RecordStore(path).list_bases()] == [good.id]
def test_the_write_is_atomic(tmp_path, monkeypatch) -> None:
"""The temp file carries the new content and the registry is swapped, so a
reader never sees a partial write and a failed write never truncates."""
path = tmp_path / "records.json"
store = RecordStore(path)
seen: list[tuple[str, str]] = []
real_replace = __import__("os").replace
def _spy(src, dst):
seen.append((str(src), str(dst)))
return real_replace(src, dst)
monkeypatch.setattr("raven.knowledge._records.os.replace", _spy)
_base(store)
assert len(seen) == 1
src, dst = seen[0]
assert src.endswith(".tmp") and dst == str(path)
assert not (tmp_path / "records.json.tmp").exists()
def test_rename_touches_only_the_two_editable_fields(store) -> None:
base = _base(store)
updated = store.rename_base(base.id, name="renamed", description="why it exists")
assert (updated.name, updated.description) == ("renamed", "why it exists")
assert (updated.embedding_model, updated.dimensions) == (base.embedding_model, base.dimensions)
assert updated.created_at == base.created_at
def test_rename_leaves_the_other_field_alone_when_it_is_not_given(store) -> None:
base = store.create_base(name="notes", embedding_model="m", dimensions=8, description="kept")
assert store.rename_base(base.id, name="renamed").description == "kept"
def test_renaming_a_missing_base_returns_none(store) -> None:
assert store.rename_base("nope", name="x") is None
def test_deleting_a_base_takes_its_documents_with_it(store) -> None:
"""Leaving them behind strands rows that list by base id: nothing can reach
them and nothing can delete them."""
base = _base(store)
other = _base(store, "other")
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=3)
kept = store.add_document(base_id=other.id, source="b.md", media_type="text/markdown", size=3)
assert store.delete_base(base.id) is True
assert store.get_document(doc.id) is None
assert store.get_document(kept.id) is not None
def test_deleting_a_missing_base_says_so(store) -> None:
assert store.delete_base("nope") is False
def test_documents_list_per_base_in_creation_order(store) -> None:
base = _base(store)
first = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
second = store.add_document(base_id=base.id, source="b.md", media_type="text/markdown", size=1)
assert [d.id for d in store.list_documents(base.id)] == [first.id, second.id]
def test_a_new_document_starts_pending_and_shows_up_in_the_queue(store) -> None:
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
assert doc.status == "pending"
assert [d.id for d in store.pending_documents()] == [doc.id]
def test_a_successful_retry_clears_the_earlier_error(store) -> None:
"""Otherwise the page shows a failure next to a document it calls ready."""
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
store.set_status(doc.id, "failed", error="embedding endpoint refused the request")
done = store.set_status(doc.id, "ready", chunk_count=7)
assert (done.status, done.chunk_count, done.error) == ("ready", 7, "")
def test_setting_status_on_a_missing_document_returns_none(store) -> None:
assert store.set_status("nope", "ready") is None
def test_a_document_left_indexing_is_requeued_on_load(tmp_path) -> None:
"""Indexing runs in the gateway process, so a document still marked
indexing at load lost its indexer with the last process. Left alone it
stays in that state for good -- reported as in progress, picked up by
nobody."""
path = tmp_path / "records.json"
store = RecordStore(path)
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
store.set_status(doc.id, "indexing")
reopened = RecordStore(path)
assert reopened.get_document(doc.id).status == "pending"
assert [d.id for d in reopened.pending_documents()] == [doc.id]
def test_a_ready_document_is_not_requeued(tmp_path) -> None:
path = tmp_path / "records.json"
store = RecordStore(path)
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
store.set_status(doc.id, "ready", chunk_count=2)
reopened = RecordStore(path)
assert reopened.get_document(doc.id).status == "ready"
assert reopened.pending_documents() == []
def test_the_requeue_is_persisted_not_just_in_memory(tmp_path) -> None:
"""A second reader must see the same queue as the first."""
path = tmp_path / "records.json"
store = RecordStore(path)
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
store.set_status(doc.id, "indexing")
RecordStore(path)
on_disk = json.loads(path.read_text(encoding="utf-8"))
assert on_disk["documents"][doc.id]["status"] == "pending"
def test_a_registry_written_before_origins_existed_still_loads(tmp_path) -> None:
"""The field has a default for exactly this: every document in such a
registry is a file, which is what the default says."""
path = tmp_path / "records.json"
path.write_text(
json.dumps(
{
"bases": {
"b1": {
"name": "handbook",
"description": "",
"embedding_model": "bge-m3",
"dimensions": 8,
"created_at": "2026-08-24T00:00:00",
"updated_at": "2026-08-24T00:00:00",
}
},
"documents": {
"d1": {
"base_id": "b1",
"source": "a.md",
"media_type": "text/markdown",
"size": 1,
"status": "ready",
"created_at": "2026-08-24T00:00:00",
"updated_at": "2026-08-24T00:00:00",
}
},
}
),
encoding="utf-8",
)
store = RecordStore(path)
assert store.get_document("d1").origin == "file"
assert store.get_document("d1").origin_ref == ""
def test_rewriting_a_document_sends_it_back_to_the_queue(store) -> None:
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
store.set_status(doc.id, "failed", chunk_count=3, error="no parser")
updated = store.update_document(doc.id, source="b.md", media_type="text/markdown", size=9)
assert (updated.source, updated.size) == ("b.md", 9)
# Back to pending with nothing counted: the text those chunks were
# embedded from is gone, and reporting them would describe a document
# that no longer exists. The old failure goes with it.
assert (updated.status, updated.chunk_count, updated.error) == ("pending", 0, "")
assert store.pending_documents() == [updated]
def test_rewriting_a_missing_document_returns_none(store) -> None:
assert store.update_document("nope", source="b.md", media_type="text/markdown", size=1) is None
def test_settings_are_written_one_field_at_a_time(store) -> None:
base = _base(store)
store.configure_base(base.id, top_k=12)
store.configure_base(base.id, chunk_size=1024, chunk_overlap=200)
kept = store.get_base(base.id)
assert (kept.top_k, kept.chunk_size, kept.chunk_overlap) == (12, 1024, 200)
# The fields nobody sent stay where they were.
assert (kept.smart_chunking, kept.separator) == (True, "\n\n")
def test_a_setting_nobody_defined_is_a_caller_mistake(store) -> None:
"""Dropping it quietly would leave a surface reporting a value it never
stored."""
base = _base(store)
with pytest.raises(ValueError, match="not a knowledge base setting"):
store.configure_base(base.id, embedding_model="something-else")
def test_a_rebuild_moves_the_model_and_requeues_everything_under_it(store) -> None:
"""The two halves are one write: a document left saying ready would be
claiming chunks that the rebuild is about to throw away."""
base = _base(store)
doc = store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=10)
store.set_status(doc.id, "ready", chunk_count=4)
rebuilt = store.rebuild_base(base.id, embedding_model="bge-m3", dimensions=1024, embedding_provider="siliconflow")
assert (rebuilt.embedding_model, rebuilt.dimensions) == ("bge-m3", 1024)
assert rebuilt.embedding_provider == "siliconflow"
kept = store.get_document(doc.id)
assert (kept.status, kept.chunk_count) == ("pending", 0)
def test_a_rebuild_survives_a_reload(store, tmp_path) -> None:
base = _base(store)
store.rebuild_base(base.id, embedding_model="", dimensions=0)
reloaded = RecordStore(tmp_path / "knowledge" / "records.json").get_base(base.id)
assert (reloaded.embedding_model, reloaded.dimensions) == ("", 0)
def test_rebuilding_a_base_that_is_gone_returns_none(store) -> None:
assert store.rebuild_base("nope", embedding_model="bge-m3", dimensions=8) is None
def test_configuring_a_base_that_is_gone_returns_none(store) -> None:
assert store.configure_base("nope", top_k=3) is None
def test_a_registry_written_before_settings_existed_still_loads(tmp_path) -> None:
"""Every field defaulted, so such a base loads with the behaviour it
already had rather than failing to load at all."""
path = tmp_path / "records.json"
path.write_text(
json.dumps(
{
"bases": {
"b1": {
"name": "handbook",
"description": "",
"embedding_model": "bge-m3",
"dimensions": 8,
"created_at": "2026-08-24T00:00:00",
"updated_at": "2026-08-24T00:00:00",
}
},
"documents": {},
}
),
encoding="utf-8",
)
base = RecordStore(path).get_base("b1")
assert (base.top_k, base.smart_chunking, base.separator) == (
DEFAULT_TOP_K,
True,
DEFAULT_SEPARATOR,
)
assert (base.chunk_size, base.chunk_overlap, base.file_processing) == (
DEFAULT_CHUNK_SIZE,
DEFAULT_CHUNK_OVERLAP,
"",
)
def test_a_new_base_starts_on_the_defaults_the_panel_shows(store) -> None:
"""One source for these numbers: the record's fields, the handlers' fallback
for a base that predates them, and the panel's Restore Defaults all have to
agree, and three copies are three chances to drift."""
base = _base(store)
assert (base.top_k, base.chunk_size, base.chunk_overlap) == (
DEFAULT_TOP_K,
DEFAULT_CHUNK_SIZE,
DEFAULT_CHUNK_OVERLAP,
)
# The overlap has to leave a chunk with something of its own in it.
assert DEFAULT_CHUNK_OVERLAP < DEFAULT_CHUNK_SIZE
def test_a_registry_this_version_writes_still_loads_on_the_previous_one(tmp_path) -> None:
"""The documented rollback. A previous loader builds each record by handing
every stored key to a dataclass constructor and drops the row when one is a
keyword it does not take -- so a field written beside the record makes
every base and document vanish from a build that is rolled back, with the
records still on disk and nothing listing them.
Stands in for that loader with the field set it accepts, which is what the
shipped build is: this asserts the stored shape, not our own reader."""
legacy_base = {"name", "embedding_model", "dimensions", "created_at", "updated_at", "description"}
legacy_doc = {
"base_id",
"source",
"media_type",
"size",
"status",
"created_at",
"updated_at",
"chunk_count",
"error",
}
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="handbook", embedding_model="bge-m3", dimensions=8)
store.configure_base(base.id, top_k=12, chunk_size=1024, smart_chunking=False)
store.add_document(base_id=base.id, source="a.md", media_type="text/markdown", size=1)
store.add_document(base_id=base.id, source="plan.md", media_type="text/markdown", size=2, origin="note")
raw = json.loads((tmp_path / "records.json").read_text(encoding="utf-8"))
assert set(raw["bases"]) and set(raw["documents"])
for fields in raw["bases"].values():
assert set(fields) <= legacy_base, f"a rolled-back loader refuses {sorted(set(fields) - legacy_base)}"
for fields in raw["documents"].values():
assert set(fields) <= legacy_doc, f"a rolled-back loader refuses {sorted(set(fields) - legacy_doc)}"
def test_the_settings_survive_the_round_trip_they_are_kept_apart_for(tmp_path) -> None:
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="handbook", embedding_model="bge-m3", dimensions=8)
store.configure_base(base.id, top_k=12, chunk_size=1024, separator="\n---\n")
doc = store.add_document(
base_id=base.id,
source="docs.md",
media_type="text/markdown",
size=2,
origin="url",
origin_ref="https://example.com/docs",
)
reopened = RecordStore(tmp_path / "records.json")
kept = reopened.get_base(base.id)
assert (kept.top_k, kept.chunk_size, kept.separator) == (12, 1024, "\n---\n")
back = reopened.get_document(doc.id)
assert (back.origin, back.origin_ref) == ("url", "https://example.com/docs")
def test_a_registry_using_none_of_them_is_written_as_it_always_was(tmp_path) -> None:
"""The sibling keys appear only when there is something to put in them, so
an installation that has touched no setting writes what it always did."""
store = RecordStore(tmp_path / "records.json")
store.create_base(name="handbook", embedding_model="bge-m3", dimensions=8)
raw = json.loads((tmp_path / "records.json").read_text(encoding="utf-8"))
assert sorted(raw) == ["bases", "documents"]
def test_a_field_from_a_later_version_is_ignored_rather_than_losing_the_row(tmp_path) -> None:
"""The mirror of the case above: losing a base because a build after this
one added a field would be the same bug in the other direction."""
path = tmp_path / "records.json"
path.write_text(
json.dumps(
{
"bases": {
"b1": {
"name": "handbook",
"description": "",
"embedding_model": "bge-m3",
"dimensions": 8,
"created_at": "2026-08-24T00:00:00",
"updated_at": "2026-08-24T00:00:00",
}
},
"documents": {},
"base_settings": {"b1": {"top_k": 9, "a_field_from_the_future": True}},
}
),
encoding="utf-8",
)
base = RecordStore(path).get_base("b1")
assert base is not None
assert base.top_k == 9
# -- folders -------------------------------------------------------------------
def test_a_document_starts_in_root(tmp_path) -> None:
"""Root is the absence of a folder, so every document ever written is
already in it and nothing had to be migrated to make that true."""
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="b", embedding_model="m", dimensions=8)
doc = store.add_document(base_id=base.id, source="a.pdf", media_type="application/pdf", size=1)
assert doc.folder_id == ""
def test_a_folder_holds_the_documents_moved_into_it(tmp_path) -> None:
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="b", embedding_model="m", dimensions=8)
doc = store.add_document(base_id=base.id, source="a.pdf", media_type="application/pdf", size=1)
folder = store.create_folder(base.id, "notes")
moved = store.move_document(doc.id, folder.id)
assert moved is not None and moved.folder_id == folder.id
assert [f.id for f in store.list_folders(base.id)] == [folder.id]
def test_a_document_moves_back_to_root(tmp_path) -> None:
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="b", embedding_model="m", dimensions=8)
doc = store.add_document(base_id=base.id, source="a.pdf", media_type="application/pdf", size=1)
folder = store.create_folder(base.id, "notes")
store.move_document(doc.id, folder.id)
back = store.move_document(doc.id, "")
assert back is not None and back.folder_id == ""
def test_a_move_into_a_folder_that_is_not_there_is_refused(tmp_path) -> None:
"""Otherwise the document is filed under an id nothing lists, which reads
to a page as a document that has vanished."""
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="b", embedding_model="m", dimensions=8)
doc = store.add_document(base_id=base.id, source="a.pdf", media_type="application/pdf", size=1)
assert store.move_document(doc.id, "nosuchfolder") is None
assert store.get_document(doc.id).folder_id == ""
def test_deleting_a_folder_returns_its_documents_to_root(tmp_path) -> None:
"""The documents stay. A folder is a label a reader put on them, and
taking the label off is not a reason to destroy what it labelled."""
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="b", embedding_model="m", dimensions=8)
folder = store.create_folder(base.id, "notes")
kept = store.add_document(base_id=base.id, source="a.pdf", media_type="application/pdf", size=1)
store.move_document(kept.id, folder.id)
moved = store.delete_folder(folder.id)
assert moved == 1
assert store.get_document(kept.id).folder_id == ""
assert store.list_folders(base.id) == []
def test_deleting_a_base_takes_its_folders(tmp_path) -> None:
store = RecordStore(tmp_path / "records.json")
base = store.create_base(name="b", embedding_model="m", dimensions=8)
store.create_folder(base.id, "notes")
store.delete_base(base.id)
assert store.list_folders(base.id) == []
def test_folders_survive_a_reload(tmp_path) -> None:
path = tmp_path / "records.json"
store = RecordStore(path)
base = store.create_base(name="b", embedding_model="m", dimensions=8)
folder = store.create_folder(base.id, "notes")
doc = store.add_document(base_id=base.id, source="a.pdf", media_type="application/pdf", size=1)
store.move_document(doc.id, folder.id)
again = RecordStore(path)
assert [f.name for f in again.list_folders(base.id)] == ["notes"]
assert again.get_document(doc.id).folder_id == folder.id
def test_a_registry_with_no_folder_writes_no_folders_key(tmp_path) -> None:
"""Byte-for-byte what the writer before folders produced, so an install
that never makes one cannot tell this shipped."""
import json
path = tmp_path / "records.json"
store = RecordStore(path)
store.create_base(name="b", embedding_model="m", dimensions=8)
assert "folders" not in json.loads(path.read_text(encoding="utf-8"))