109 Commits

Author SHA1 Message Date
Axton Ji
04eb2ac82e fix: batch indexing journal writes for per-document status updates (#3137)
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>
2026-12-01 16:56:02 +08:00
iron ox
8fe2567c65 fix(knowledge): report live progress for LlamaIndex folder batches (#2483)
Forward embedding-batch progress through DocumentAdder so LlamaIndex folder
syncs and multi-file uploads no longer stay at 0% until the whole batch returns.

Co-authored-by: zhouyao01 <zhouyao01@mucang.cn>
2026-12-01 15:01:46 +08:00
AleFlyX
e542e3ff0e fix(knowledge): drop visual assets on every document-delete path (#3022)
* fix(knowledge): drop visual assets on every document-delete path

Extracted figures are tracked in `visual_assets/` (manifest + image files) and
were only cleaned by the HTTP delete-file route, which called
`VisualAssetStore.remove_source` itself. `remove_raw_document` has three
callers - that route plus the GitHub and web source syncs - so the two sync
paths deleted the document and left its figures and manifest entries behind
forever. Images are capped at 5 MB each, so a sync that drops figure-heavy
documents leaks a lot of disk.

Reproduced before the fix: a KB with one raw PDF and a matching asset entry,
then `remove_raw_document(kb, doc)` (exactly what both syncs do) -> the doc was
gone while the asset file and its manifest entry both remained.

Cleanup now happens in `remove_raw_document`, the single layer all three
deletion paths share, keyed by the module's existing `_raw_hash_key` - the same
rule indexing uses to record `source_path`, so nested raw/ paths cannot be
missed. The route's now-redundant call is removed rather than left as a second
owner: it also removes a second, lexical relative-path computation, and the old
uncaught call could 500 a delete on a corrupt manifest, which contradicts the
"cleanup never fails a user's delete" contract.

Best-effort like the surrounding code: a corrupt or read-only manifest logs a
warning and never turns a delete into an error. `VisualAssetStore.__init__`
only assigns paths, and `remove_source` returns before writing when no entry
matches, so KBs that never had images are not given an empty `visual_assets/`
directory (pinned by a test).

Verified: 7 new tests; mutation check shows disabling the cleanup fails 4 of
them. Independent checks: nested `papers/2024/` asset removed while a sibling
document's asset is preserved; no `visual_assets/` created for an image-free
KB; re-running the original repro now reports no leak.
Tests: 264 passed (knowledge, visual assets, source sync, HTTP file deletion).

Note: assets for an older parser signature are deliberately kept so a rollback
to an older index version still resolves its figures; that is retention, not a
leak, and is unchanged here.

* fix(api): 更新路由索引指纹

重新生成 knowledge 路由变更后的索引。原生引擎和路由加载器的 18 个测试均已通过。

---------

Co-authored-by: zszz3 <zszz3@users.noreply.github.com>
2026-11-30 15:37:35 +08:00
AleFlyX
5ff2627aee fix(knowledge): reclaim parse cache when a document or KB is deleted (#2941)
The parse cache is content-addressed and has no eviction of any kind: no size
cap, no TTL, no LRU, no CLI command, no settings entry. Neither deleting a raw
document nor deleting a whole knowledge base removed anything from it, and the
only cleanup that exists (clean_rag_storage) removes index storage - not the
parse cache - and is CLI-only. A deleted KB therefore kept its entire derived
parse output on disk forever.

Measured with a realistic document: a 30-page PDF with ~18 extracted images
leaves about 6.5 MB under parse_cache/. 64 such documents accumulate ~418 MB
that is never reclaimed; the directory only grows.

cache.reclaim_sources(paths, cache_root=...) removes the
<parse_cache>/<hash[:2]>/<hash>/ shard for each document being deleted - every
parser signature for that source, since the cache is derived and the next parse
recreates what it needs. It hashes the bytes while they still exist, because
the cache key is the content hash. Wired into two call sites, both before the
bytes disappear:

- remove_raw_document (single file, before unlink())
- KnowledgeBaseManager.delete_knowledge_base (every raw document, before the
  KB directory is removed)

The cache root is derived from the KB directory (a sibling of knowledge_bases/)
rather than from the ambient path service, because requests served from the
knowledge-base library run in the account workspace scope. Deriving it from the
request scope would reclaim another workspace's cache while leaking this KB's
own. KB deletion enumerates exactly what rmtree removes: dotfiles included,
symlinks skipped because only the link goes away.

Reclaiming is scoped strictly to the hashes of the files being deleted, so
nothing else under the cache root is touched. The cache is shared across all
parse consumers in the workspace (KB indexing, chat attachments, reading
figures), so a byte-identical copy loses its entry too and is re-parsed once on
next use - slower, never incorrect. Proving liveness would mean hashing every
live source on every delete, and metadata.json only records documents that
indexed successfully; that tradeoff is documented on the helper and at both
call sites. The key is a truncated 64-bit hash; a collision costs one extra
re-parse, never wrong output.

Best-effort by contract: an unreadable source, a locked shard (a stale Windows
handle is the common case) or a missing cache root is logged and skipped, and
both call sites additionally wrap the call, so no cache failure can fail a
user's delete.

Note: this reclaims on delete; it does not bound growth of the live cache. A
size cap / LRU sweeper is a separate change and should be its own issue (the
scope split is recorded on #2946).

Verified on the current dev base (14796c70f): 14 new tests; mutation checks show
disabling the helper at either call site fails its positive-reclamation test.
A workspace/library-view reproduction (real ContentWorkspaceService, account
scope, KB stored in a workspace) confirms the KB's own shard is now reclaimed
while an account-level lookalike shard is left alone. tests/knowledge: 205
passed, 6 pre-existing failures (same as dev, missing llama_index/jose). ruff
check/format clean with the pinned 0.16.0.
2026-11-30 14:17:47 +08:00
Chen jizhou
4d4a0b7524 fix: preserve embedding checkpoint pointer across preflight failures (#2698)
Co-authored-by: chen-12-03 <184723954+chen-12-03@users.noreply.github.com>
2026-11-28 18:23:30 +08:00
lazytalk
9e20ebc9d7 fix(knowledge): skip unreadable index versions instead of failing the KB list
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>
2026-11-09 22:49:11 +08:00
RRFZ
0c8593bf00 fix(knowledge): stop Windows readers from wiping kb_config.json
On Windows, file_lock_shared took msvcrt LK_NBLCK, which is an
exclusive, mandatory byte-range lock (msvcrt has no shared lock). A
reader that overlapped another reader failed with PermissionError,
_read_and_reconcile_config mapped that to an empty catalog, and the next
update_kb_status auto-registered its KB into the empty catalog and saved
it, dropping every other knowledge base's entry from kb_config.json.

Writers already replace the file atomically, so readers need no lock:
take none on Windows. POSIX keeps its LOCK_SH.
2026-10-31 21:22:25 -04:00
fanjiahe
cfd1e2e3b6 fix: publish one LlamaIndex version per folder sync
Linked-folder sync wrote a full snapshot for every file and never deleted the old ones. Index a staged batch in one publish and keep the newest three snapshots per embedding signature.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-31 00:53:47 +08:00
xunguangzlj-cloud
f06a84e95a fix: 暂存重试复用发生文件名冲突的文档 2026-10-29 00:17:20 +08:00
Bingxi Zhao (Frank)
9aadac3e3b merge: integrate current dev with modular installation 2026-10-28 01:23:48 +08:00
Bingxi Zhao (Frank)
fbab59acbf feat: modularize installation and enforce feature dependency boundaries 2026-10-28 01:02:29 +08:00
Bingxi Zhao
619888b731 Merge pull request #2027 from evan188199-tech/codex/feat/rag-embedding-resume
fix(rag): resume embedding checkpoints (#1983)
2026-10-28 00:21:26 +08:00
ZQR1101
8899ae6df6 fix(knowledge): keep same-named documents when creating a KB
`kb create --docs-dir` staged every source at `raw/<basename>` with an
unconditional copy, so a docs tree with one `full.md` per volume kept only
the last file and still reported success. Both KB entry points now share one
staging rule (`knowledge/staging.py`): a taken name is reused only when the
content matches, otherwise the newcomer gets a free sibling name, so nothing
the user asked to index is dropped.

Issue: #2041
2026-10-24 17:44:13 +00:00
XZH
f657d343ee fix(rag): resume embedding checkpoints 2026-10-22 14:49:26 -07:00
Bingxi Zhao (Frank)
c3b98baf34 fix(parsing): align MinerU deadlines and retain terminal errors (#1982) 2026-10-19 01:52:28 +08:00
Bingxi Zhao
c0c5cbd5a7 Merge pull request #1858 from dajiaohuang/fix/marginnote-delete-confirmation
fix(knowledge): confirm before deleting MarginNote state
2026-10-19 00:24:20 +08:00
Mohammad Hijjawi
b273dc584a fix: retry transient locks and decode UTF-8 when reading the indexing journal
load_run() read .indexing-run.json and .indexing-cancel.json with a bare
Path.read_text(), so a brief Windows sharing lock (antivirus, indexer, a
concurrent reader) failed the safety check at once with "Indexing journal
is unreadable", and the locale default encoding garbled or rejected the
UTF-8 that atomic_write_json writes (a document named "ÁLGEBRA.pdf" makes
every check fail under cp1252).

Add file_io.read_text(), which reads UTF-8 and shares the bounded
PermissionError backoff already used by _atomic_replace(). Missing files,
corrupt JSON and locks that outlast the backoff keep their existing
behaviour.

Closes #1912
2026-10-11 01:23:40 +01:00
dajiaohuang
2eefb2c935 Merge commit '6cf793bd868ba5ecbe64722936d4be8fab5a01df' into fix/marginnote-delete-confirmation 2026-10-08 12:40:43 +08:00
dajiaohuang
857b7b48e7 fix(knowledge): confirm MarginNote deletion before removing data 2026-10-08 12:40:43 +08:00
Bingxi Zhao (Frank)
e79e1b0ad2 fix(knowledge): make long-document indexing recoverable and publication verified (#1612) 2026-10-08 08:10:40 +08:00
evan188199-tech
50a3ba4e4d fix(knowledge): surface swallowed KB status, progress and folder-sync failures (#1706)
* fix(knowledge): make update_kb_status write failures observable

The ready-transition metadata refresh swallowed every exception
(`except Exception: pass`), and a kb_config.json persist failure
surfaced only as an opaque raise inside fire-and-forget callers, so
a lost status update left the persisted KB state stale with no
diagnostic.

- Log a warning naming the KB when the best-effort ready-transition
  metadata refresh fails, instead of silently passing.
- Log an error with the KB name and status when persisting the
  config fails, then re-raise so callers still receive the exception
  (the write is authoritative, not best-effort).

Tests: a persist failure is logged and re-raised; a metadata refresh
failure is logged and does not propagate.

* fix(knowledge): make progress WS failures visible instead of silent

The websocket_progress endpoint swallowed five failure points with
`except Exception: pass`: timestamp parsing (x2), error-frame delivery,
socket close, and user-context reset. A corrupt progress snapshot or a
broken teardown path therefore vanished without a trace.

- Share a _progress_age_seconds helper for both freshness checks: narrow
  the catch to (TypeError, ValueError), keep the inactive/stale fallback,
  and log unparseable timestamps at warning level.
- Reuse the already-parsed snapshot age in the replay decision, so one
  corrupt timestamp warns once per connection instead of once per
  freshness check.
- Trace failed error-frame delivery and failed close at debug level
  (usually an already-disconnected client, not a fault).
- Log a failed reset_current_user at warning level: leaking the user
  context is a real fault, not a disconnect.

Tests: malformed timestamp degrades with a warning; cleanup failures are
logged and never propagate; normal disconnects stay silent.

* fix(knowledge): stop swallowing a failed reindex error-progress write

The reindex failure path wrapped its ProgressTracker ERROR update in
`except Exception: pass`, so when that write itself failed the rebuild's
failure alert disappeared and the KB progress view silently stayed stale.
Log a warning instead; the task-level error status remains authoritative.

* fix(knowledge): log folder sync state recording failures

update_folder_sync_state() swallowed per-file mtime recording errors
with 'except Exception: pass', so a file whose state could not be
recorded silently degraded the persisted sync state while last_sync
still advanced. Log the failure at WARNING and keep the un-recorded
fallback so the next scan re-syncs the file.

* test(codebuddy): make credential fixture expiry relative to now

test_load_credentials_parses_session wrote a hard-coded expiresAt of
1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is
False. Once that instant passed the assertion flipped, so the test now
fails on every Python version for every branch.

Derive expiresAt / refreshExpiresAt from time.time() so the fixture
always describes a live session, and assert against the value written.

---------

Co-authored-by: XZH <cto@xzh.ai>
2026-10-07 20:22:32 +08:00
Bingxi Zhao (Frank)
4d7b080fbe fix(knowledge): reuse catalog probes without blocking the API (#1711) 2026-10-04 18:04:10 +08:00
Bingxi Zhao (Frank)
176257b1f8 style: format knowledge source integrations 2026-09-27 11:15:15 +08:00
Bingxi Zhao (Frank)
a824e4b01f fix(knowledge): preserve moved KB retrieval and scoped jobs 2026-09-27 11:04:33 +08:00
Bingxi Zhao (Frank)
64c2316093 Add connected Kiwix ZIM knowledge sources 2026-09-27 11:01:04 +08:00
FriedorixNietzsche
80da6cee23 fix: support Windows data volume permission checks 2026-09-25 18:24:37 +08:00
Bingxi Zhao (Frank)
55490af65e Merge issue fixes into PR synthesis
Combine knowledge bootstrap coverage and preserve later progress-isolation tests, native notebook tooltip, and locale-aware tool-hint fallback. Regenerate frontend contracts and align test fixtures with merged APIs.
2026-09-23 12:06:19 +08:00
Bingxi Zhao (Frank)
ce02c1fdbb fix(knowledge): track confirmed files during empty-index bootstrap (#1481) 2026-09-23 11:12:10 +08:00
Bingxi Zhao (Frank)
2faceb1f5a fix(knowledge): persist reindex hashes only for indexed sources (#1481) 2026-09-23 11:00:54 +08:00
Bingxi Zhao (Frank)
064034a283 Merge branch 'codex/evan-backend-prs-20260923' into codex/pr-batch-root
# Conflicts:
#	deeptutor/api/routers/settings.py
#	tests/api/test_settings_router.py
#	web/components/notebook/NotebookRecordRow.tsx
#	web/components/settings/SettingsOverview.tsx
#	web/context/app-shell-storage.ts
#	web/features/knowledge/api/sources.ts
#	web/features/settings/store/SettingsStore.tsx
2026-09-23 10:56:37 +08:00
Bingxi Zhao (Frank)
777babc382 Preserve linked-folder sync snapshots and empty KB bootstrap 2026-09-23 10:49:20 +08:00
Bingxi Zhao (Frank)
e7f9528335 Merge PR #1459 runtime UID remapping 2026-09-23 10:28:56 +08:00
Bingxi Zhao (Frank)
1dff2a2424 Merge commit 'refs/pr/1385' into codex/evan-backend-prs-20260923 2026-09-23 10:28:46 +08:00
Bingxi Zhao (Frank)
b38a2245eb Merge PR #1334 linked folder manual sync 2026-09-23 10:28:15 +08:00
Bingxi Zhao (Frank)
3800028fa8 merge: integrate LightRAG roles with embedding compatibility 2026-09-21 13:36:18 +08:00
NoxsMedia
8d2c452ef5 fix: display the bound LightRAG version in index provenance 2026-09-21 03:10:48 +00:00
NoxsMedia
0ce3f5a713 fix: display the bound version alongside pinned LightRAG roles 2026-09-21 03:10:48 +00:00
NoxsMedia
1c8a29d257 fix: retain bound index provenance and embedding-only controls 2026-09-21 03:04:13 +00:00
NoxsMedia
77392102f2 fix: keep recovered LightRAG index policy and provenance aligned 2026-09-21 03:02:30 +00:00
NoxsMedia
ac8cc4a97d fix: preserve selected embeddings in confirmed LightRAG rebuilds 2026-09-21 02:57:39 +00:00
NoxsMedia
73e062c594 fix: preserve LightRAG compatibility with per-KB embedding bindings 2026-09-21 02:45:23 +00:00
Bingxi Zhao (Frank)
da856ad670 release: v1.6.9
Ship folder-based workspaces and data migration, daily practice, redesigned
provider and model settings, and streaming conversation improvements.
Synchronize README translations and document the archive/permanent-delete
upgrade behavior in assets/releases/ver1-6-9.md.

Reduce initial JavaScript by deduplicating English resources and loading
animation features after hydration. Keep the existing route size budgets.
Update regression fixtures and browser audits for scoped URLs and the new
settings and learning interfaces.
2026-09-21 02:30:40 +08:00
Bingxi Zhao (Frank)
c547a5a31c fix: resolve verified learning, ingestion and delivery regressions
Bind mastery drafts before their opening turn and preserve stored session modes.
Track chat duration from submission through terminal completion. Run async reading
extensions on their event loop and allow retries after cancellable timeouts.
Allow first uploads into empty LlamaIndex knowledge bases, preserve Telegram
thread routing, parse embedding Retry-After dates, and enforce robots rules and
host pacing during documentation crawls, including redirects.

Fixes #1461
Fixes #1458
Fixes #1451
Fixes #1448
Fixes #1392
Fixes #1429
Refs #1435, #1412

Reuses contributions from PRs #1462, #1452 and #1403.

Co-authored-by: sjagadee <srini.jagadeesh@gmail.com>
Co-authored-by: AoHanBei <dongaohan21@gmail.com>
Co-authored-by: Gao-Chenkai <DevChenkai@outlook.com>
2026-09-15 20:06:57 +08:00
Gao-Chenkai
388399c3a1 fix(docker): remap PUID/PGID for Unraid bind mounts (#1458)
Empty LlamaIndex KBs and UID-mismatched volumes were reported as
"not initialized". Fail-fast on unwritable data dirs and remap the
non-root deeptutor user instead of swallowing chown failures.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 22:13:48 +08:00
XZH
90b99187d1 feat(web-source): add durable sync scheduling 2026-09-10 17:31:03 -07:00
Gao-Chenkai
d033272f93 feat(knowledge): add linked folder manual sync 2026-09-09 21:24:41 +08:00
NoxsMedia
2d7904e916 chore: sync PR #1281 with current dev 2026-09-07 23:33:46 +00:00
NoxsMedia
7266c7aacf chore: sync PR #1265 with current dev 2026-09-07 23:33:46 +00:00
Bingxi Zhao (Frank)
e7d04fccfc fix(knowledge): validate KB names on the manager, and let a bad one be deleted
A knowledge-base name is three things at once: a kb_config.json key, a
directory under data/knowledge_bases, and a path segment in every per-KB API
route. `validate_knowledge_base_name` exists to keep those three uses
compatible — its docstring says so — but it was called from one of the eight
HTTP entry points that can write a name into the config. The seven connect-*
endpoints (Obsidian, MarginNote, folder, LightRAG server, WeKnora, IMA, and
the subagent connection) did `(name or "").strip()` and wrote the result.

A name holding a "/" registers fine that way and is then unreachable.
uvicorn percent-decodes the path before routing, so %2F is a real separator
by the time Starlette matches `{kb_name}` — compiled to `[^/]+`, which cannot
span it. All 29 per-KB routes 404, delete included, while the list endpoint
takes no path parameter and keeps rendering the KB. Connected KBs are also
exempt from the orphan prune, so nothing collects it either: visible, unusable,
and removable only by hand-editing kb_config.json.

Two changes, both needed. Validation moves onto the eight `register_*`
methods, which is the seam every route already goes through — no route file
changes, since they all map ValueError to 400 — and the now-unreachable
"name is required" guards go with it. And a path-free
`POST /knowledge-bases/delete` gives the entries that predate the guard a way
out; a body is never split into segments. Widening the path route to
`{kb_name:path}` would not work: it is declared ahead of the DELETE routes
for linked folders, GitHub sources and web sources, and a greedy converter
would silently swallow all three.

Two smaller fixes ride along. The delete handler's catch-all swallowed its
own HTTPException and answered 500 with "404: ... not found" in the detail;
it now re-raises. And CreateKbModal states the rule under the field instead
of letting an untranslated English 400 be the first the user hears of it.

test_marginnote4_kb's store-collision case used "My Lib" / "My/Lib"; the
slash is now refused before that guard is reached, so it uses "My.Lib" —
still a name the rule allows, still sanitized to the same My_Lib.db.
2026-09-08 00:31:59 +08:00
Bingxi Zhao (Frank)
da285f236b refactor(knowledge): give connected-KB adoption a public entry point
Provisioning reached across modules for `KnowledgeBaseManager.config` and
`_save_config()`, which put a partner-workspace concern inside the manager's
private state. `register_connected_entry` states the operation instead: adopt
an entry that already exists, refuse anything that is not a pointer KB, and
report whether it was new so provisioning stays idempotent the way the
copytree branch is.
2026-09-08 00:00:27 +08:00