IndexingRun.document() re-reads the journal and atomically rewrites the
whole .indexing-run.json on every call. The LlamaIndex loader marks each
accepted source "embedding" in a synchronous loop on the event loop, and
publication marks every loaded Document (one per page) "completed" the
same way, so recording n statuses costs O(n^2) bytes of I/O with no
await in between. On a 4,320-document reindex this held the loop for
over 100 s, /health/ready stopped answering, and the desktop supervisor
killed the core.
Add IndexingRun.documents(sources, status, **details), which applies one
status to many sources under a single ownership check and a single
journal write, and use it from the loader, the LlamaIndex publication
step and the RAG service's indexed-file callback. document() now
delegates to it, so single updates behave as before.
Fixes#3046
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
A KB-list / get_info sweep probes every version-N directory of every KB,
because the UI renders readiness per version. The docstore count cache is
keyed per version directory, so its capacity has to cover the whole
catalogue, not a single KB's worth.
At the old fixed 128 slots a real installation (13 KBs, 310 version
directories -- #2772) exceeded the working set on every sweep: each probe
evicted exactly what it had just read, the hit rate stayed at a permanent
0%, and every UI navigation re-parsed every multi-MB docstore.json. On a
memory-constrained host that showed up as a pinned event loop and hundreds
of GB of disk reads.
Raise the capacity to 4096. Each entry is a path plus an int, so this costs
about a megabyte even well above the working set.
Reproduced against v1.7.3 with a fixture matching the report (13 KBs, 310
versions, 52 MiB of docstore.json), replaying inspect_kb_versions() per KB:
before: 310 / 310 / 310 / 310 / 310 docstore parses per sweep, 0.0% hit rate
after: 310 / 0 / 0 / 0 / 0 docstore parses per sweep, 100% warm
A rewritten docstore still invalidates correctly (doc_count 400 -> 1), and
unchanged versions stay cached. The new regression test builds 2 KBs x 100
versions, which is above the old cap, and fails on the unfixed code
(400 parses instead of 200).
Closes#2772
* feat(rag): support local rerankers for LightRAG queries
Allow administrators to select a cross-encoder alongside the native LightRAG role models. Run scoring in a reusable worker and partition cached answers by reranker so model changes take effect on existing indexes.
Refs #2701
* fix(api): refresh the router index for LightRAG settings
* fix(rag): run LightRAG reranking in the shared reranker worker
anyio's process pool re-runs the server's __main__ file by path. When the
backend runs as `python -m deeptutor_cli.main serve` (the desktop app),
that file's relative imports fail, so every rerank call failed with
'Error during worker process initialization' and LightRAG silently kept
the original chunk order. Reuse the python -m reranker worker that the
LlamaIndex pipeline already uses.
---------
Co-authored-by: lipeih <lipeihan@eazytec.com>
Co-authored-by: zszz3 <zszz3@users.noreply.github.com>
* fix(mastery): grade within the objective's covered and own scope
- Reuse the preserved objective-scoped packet for an objective request
after a focus preparation replaced the live slot, and do not rebuild
an incomplete objective packet whose fingerprints are unchanged (#2363).
- mastery_assess grades a concept/design explanation against the covered
facets of an incomplete objective packet, records that scope, and
returns a structured coverage_gap result instead of a bare refusal.
- Tell the learner when an answer was not recorded or was graded only
against the covered part.
- Give the judge sibling objectives as out of scope and return the
single missing element with a next_step to ask for exactly it (#2364).
* test(mastery): cover the focus-only assessment deadlock from #2905
A complete focus-scoped packet with no assessment slot gets a structured
coverage_gap on every repeated mastery_assess, with no judge call and no
recorded evidence. One objective preparation then grades the retained
explanation together with the next reply.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(mastery): make the missing-element step the assess instruction
Since dev added a generic instruction to every final mastery_assess
payload, a non-passing verdict carried two competing moves: next_step
asked for exactly the named missing element (#2364) and instruction
asked the learner to explain the objective again. While the gate is not
cleared, the targeted step is now also the instruction, and it says to
record the reply with mastery_assess.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(mastery): say when an unclear explanation is kept for grading
A non-final verdict in a session keeps the explanation and grades it
together with the follow-up, so the generic "not recorded, progress
unchanged" notice misled the learner into repeating the whole answer.
Add an assessment_needs_clarification notice (en/zh) for that case; an
explanation outside a session keeps the not_recorded notice.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(mastery): preserve the missing assessment element on replay
---------
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
Co-authored-by: Qiuner <wdst3635@163.com>
* fix(rag): keep figure captions out of the chunk metadata budget
Figure documents carried the caption, asset ids, bbox, source locator and
absolute path in metadata that LlamaIndex counts against every chunk. A long
caption (common for CJK textbook figures) pushed the metadata past the
default 512-token chunk size, so SentenceSplitter raised "Metadata length
(...) is longer than chunk size (512)" and the whole indexing run failed.
Keep those keys on the node for citations and pixel delivery, but exclude
them from the embed and LLM metadata text. The caption is already part of
the document text, so retrieval content is unchanged.
Closes#2865
* test(rag): split sentences without NLTK in the caption budget test
The new regression test ran SentenceSplitter with its default punkt
tokenizer, which loads NLTK data. CI runners refuse that data, so the
test failed with LookupError on all Python versions. Pass a regex
sentence splitter instead. The test still fails without the loader fix.
EngineDetail renders the readiness panel for every engine, and its check button calls /api/knowledge-bases/rag-pipelines/{provider}/preflight, which runs engine_preflight() -> _PREFLIGHTS[normalize_provider_name(provider)]().
weknora and kiwix are in KNOWN_PROVIDERS but were never registered in _PREFLIGHTS, so the lookup raised KeyError and the route answered 500 for those engine pages.
One shared _connected_preflight now reports them ready: each knowledge base supplies its own server URL and credentials, validated by the connect probe, so nothing is configured account-wide. This matches doctor.py, which already skips these providers in its preflight loop.
The new test walks KNOWN_PROVIDERS and asserts every entry returns a report, so a future provider constant cannot silently miss the registry again.
Co-authored-by: enlightenmengt2 <227120787+enlightenmengt2@users.noreply.github.com>
* fix(rag): avoid NLTK regex CPU timeout during splitting and clean failed version dirs
* fix(rag): construct PunktSentenceTokenizer directly without globals_helper stopwords
Batch resumable embedding checkpoints and write the BM25 sidecar once after the final checkpoint, carrying over #2903. 45 targeted tests passed with the PR applied to dev. A 19-source rebuild retrieved the last source from the persisted BM25 index.
Mastery Path preparation looked up a knowledge base's index by the global embedding signature. PageIndex, GraphRAG and LightRAG versions carry a provider signature instead, and a LlamaIndex knowledge base can be bound to another embedding, so a ready index was rejected with 'no compatible completed index'. Preparation now resolves the index the way the provider reads it: the KB's bound embedding for LlamaIndex, the newest provider-ready version otherwise. Fixes#2895.
* fix(mastery): name the recovery step when assessment evidence is mis-scoped
The focused-teaching refusal that blocks mastery_assess said only to prepare
assessment-bound evidence, so a session that had only ever prepared focused
packets retried the same call and the learner stayed stuck. Point the refusal
at the preparation that actually clears the gate.
* fix(mastery): avoid misleading recovery for incomplete evidence
Split focus-scoped and incomplete objective-scoped assessment refusals so
only focused packets are told to prepare without a focus. Surface missing
coverage for incomplete objective packets and pin the diagnostic with a
regression test.
---------
Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
#2708 set enable_rerank from whether a rerank model is wired, which also
overrode LightRAG's RERANK_BY_DEFAULT switch once a reranker exists. Only
turn rerank off when no model is wired and otherwise leave LightRAG's
default in place.
LightRAG 1.5.7 defaults enable_rerank on, so query_with_sources emitted a
per-query warning whenever no rerank model was configured. Gate the flag
on the presence of a callable rerank_model_func so the default deployment
stops warning without changing behavior for anyone who wired a reranker.
Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
Integrate AleFlyX's staged sidecar write from PR #2903 with the batched checkpoints in PR #2837. Rebuild the sidecar after the final checkpoint, including when resuming a fully checkpointed candidate.
Declare document-scope support at the pipeline contract and reject unsupported scoped queries before rewrite/retrieval; verify empty scopes also fail closed (29 retrieval tests and 10 service tests passed).
A pending quiz card stores the source snapshot it was verified against,
including a fingerprint of the whole published KB index. Adding any
document to that KB changed the fingerprint, so every grade failed with
"Prepare the lesson again" - which refreshes only the lesson packet,
never the card - and the learner's answer could not be recorded.
An issued question is now bound to the pages it cites: when the index
changed but each cited page (KB, document, page, source digest) is still
published unchanged, the question validates and is graded. If a cited
page did change, the error says so and names the recovery tools.
Lesson packets and question issuance keep the strict whole-index check;
objective, answer-key and scope gates are unchanged.
The source selector may ask for an adjacent page ("neighbor": -1 or 1) as
figure/table context. When that page does not exist, for example past the
last page of a PDF, located_sources raised "The requested neighboring page is
unavailable" and the whole preparation was discarded, including the pages
that were actually chosen. On a real course this failed preparation for 4 of
19 concept/design objectives; with the fix, 3 of them prepared complete
lessons and the fourth reached an unrelated coverage gap.
Skip the unavailable context page and keep the chosen pages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
prepare_lesson tells the model to pick at most MAX_LESSON_PAGES pages, but
models regularly return more (a free reasoning model did so in most runs on a
real course). The whole preparation then failed with "Invalid source selection
count: too many distinct physical pages", and the tutor retried it in a loop.
Keep the model's ranked picks within the cap and drop context-only neighbour
pages first. The lesson stays bounded; every kept page is still inspected.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A knowledge base whose data files are unreadable (for example root-owned
files in a container whose app runs as uid 1000) used to take down the
entire KB catalogue: list_kb_versions() -> _read_json() -> Path.exists()
raised PermissionError, so list_knowledge_bases() and the web-source
scheduler failed for every KB.
- _read_json() opens the file directly and treats FileNotFoundError as
"no metadata"; other OSError/ValueError degrades to a warning. This also
avoids Path.exists(), which propagates EACCES on Python >= 3.8.
- _is_storage_ready(), _flat_version_dirs() and list_kb_versions() skip
unreadable versions with a warning instead of raising.
- KnowledgeBaseManager._list_knowledge_bases() isolates per-KB failures
and an unreadable base directory, keeping the rest of the catalogue.
Tests cover unreadable metadata, an unreadable version dir, an unreadable
storage probe, and a manager listing with one unreadable KB.
Co-Authored-By: Claude Code <noreply@anthropic.com>
GitHub source sync kept only .md and .markdown, so a docs glob of *.mdx
reported success with zero files and left raw/ empty. Re-index then failed
because no supported source files were present. Treat .mdx as text next to
Markdown in the sync filter, the knowledge-base file router, and the chat
attachment list that mirrors it.
Fixes#2552
source_path alone is a document scope, not a visual request: an ordinary
text query with no page, figure, region or asset_id selector now stays on
the text retrieval path, restricted to that one document, instead of
entering exact-source visual inspection and failing reference_required.
- RAGTool routes source_path-only queries to a scoped semantic search that
verifies the source exists (and its source_hash when given), forwards
document_keys to the backend, and never falls back to a whole-KB search:
a backend that cannot enforce the scope, or a document with no matching
passage, fails explicitly (source_scope_unsupported /
source_scope_no_match) with foreign passages withheld.
- LlamaIndex scoped retrieval now recognises plain-text documents, which
carry only file_path metadata, by their raw-relative position — never by
bare basename, so sub/notes.txt does not leak into a notes.txt scope —
and admits nodes without a page_status.
- Tool schema description and en/zh prompt hints state the contract;
selector-contract tests cover the scoped text path and a new suite
covers raw-relative scope matching.
search_knowledge returns folder matches inside info_list with a folder_
media id and media_type 99, and no folder_id. Those were parsed as
documents, so retrieval spent the hydration budget on get_media_info
failures and reported content_unavailable.
Fixes#2326
The LightRAG index probe reported doc_count=None for every native-layout
index. _lightrag_doc_count read kv_store_doc_status.json from the version
root, but native LightRAG keeps its KV stores under a deeptutor_<hash>
workspace subdir; every other reader (has_output, failure_summary,
document_error) resolves that subdir via storage._store_root first.
Move the count into the storage module as a public doc_count() that
resolves the store root the same way, and have index_probe delegate to it.
A ready native index now reports its real count instead of None, so the KB
version list, last_indexed_count and linked-folder probe stop falling back
to a raw-file guess.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
build_pdf_documents() ignored MinerU list_items, so bibliography entries
on type=list / sub_type=ref_text blocks never reached the chunker.
Page-number, header, and footer blocks were indexed instead.
Fixes#2222