Repository navigation
feat(knowledge-base): improve structured chunking, indexing, and progressive retrieval - #2943
Zxf-xufeng wants to merge 0 commit into
Conversation
hidb4ai
left a comment
There was a problem hiding this comment.
The structured retrieval approach is useful, but parsing termination and complete pagination need fixes before merge. See the three reproduced findings below. Native OceanBase validation also reaches a failing hybrid-score assertion in tests/knowledge_base/test_sql_backends.py:97 after the new weighting changes; reconcile the intended score contract and its acceptance test. The branch currently conflicts with master in content.py and service.py.
| avail = max(32, maximum - len(anchor) - 4) | ||
| while len(seg) > avail: | ||
| segments.append(seg[:avail]) | ||
| seg = f"{col_prefix}: {seg[avail:]}" |
There was a problem hiding this comment.
[P1] Ensure oversized-cell splitting always makes progress
With the default max_chars=360, parsing "| id | " + "h" * 400 + " |\n| --- | --- |\n| key | value |\n" never completes. Here the column-name prefix is longer than avail; each iteration removes avail characters and prepends an even longer prefix, so seg grows instead of shrinking. I reproduced this through parse() with a two-second interrupt; the base implementation returns two chunks for the same input. An accepted Markdown upload can therefore keep its parsing worker busy and grow memory indefinitely. Bound the repeated prefix and guarantee consumption of the remaining value on every iteration, or reject the input before entering this loop.
There was a problem hiding this comment.
Reproduced again on current head ba5e160: the public parse() call with the 400-character second column header still requires interruption after two seconds. The splitter still prepends a prefix longer than the consumed slice, so the existing P1 remains unresolved.
| if len(items) >= limit: | ||
| break | ||
| has_legacy = bool((cfg.get("value") or {}).get("has_legacy_unindexed")) | ||
| next_cursor = items[-1]["relative_path"] if len(items) == limit and len(rows) > len(items) else None |
There was a problem hiding this comment.
[P2] Use a cursor that distinguishes documents with the same path
Document identity includes the collection, so two collections in one Scope can both contain a.md. The query sorts by path/document/result, but this cursor retains only the path and the next query uses relative_path > cursor. In a SQLite-backed reproduction with c1/a.md, c2/a.md, and c1/b.md, an unpaginated tree returns three documents while following limit=1 pages returns only two: the second a.md is permanently skipped. Preserve the full stable ordering identity in the cursor so pagination can enumerate every active document.
There was a problem hiding this comment.
Revalidated on ba5e160 through a real authenticated Server and spawned Worker with the actual local BGE embedding model. Upload plus directory import produced paths [a.md, a.md, b.md]; GET tree returns all three with limit=100, but following limit=1 cursors returns only [a.md, b.md]. The existing pagination defect remains reproducible across the HTTP boundary.
| if direction in {"in", "both"} and rel_path and len(items) < limit: | ||
| remaining = limit - len(items) | ||
| path_hash = hashlib.sha256(rel_path.encode("utf-8")).hexdigest() | ||
| in_rows = await self.store.links_in(scope, coll_id, path_hash, after_link_id=cursor, limit=remaining * 3) |
There was a problem hiding this comment.
[P2] Preserve direction when paginating the combined link list
For the default direction=both, outgoing links are emitted first, and their last link_id is then reused as the lower bound for incoming links. These are independently ordered sets: an incoming link with an ID below the last outgoing ID can never be returned. With one outgoing and nine active incoming links in SQLite, the full response contains ten links but following limit=1 cursors returns only three. Use a globally consistent ordering or a cursor that tracks the direction and its position; do not discard incoming IDs based on an outgoing cursor.
There was a problem hiding this comment.
Revalidated on ba5e160. The real SQLite service probe still returns 10 links unpaginated versus 3 when following limit=1 cursors. This time the real authenticated HTTP Server/Worker probe also reproduced the loss: the full response has one outgoing and one incoming link, whereas following limit=1 cursors returns only the outgoing link. The incoming ID sorts below the outgoing cursor.
hidb4ai
left a comment
There was a problem hiding this comment.
Revalidated ba5e160. The existing nonterminating parser, tree pagination, and combined-link pagination findings remain reproducible. The actual Server/Worker/local-model HTTP flow returns 3 documents unpaginated but only 2 through tree cursors, and returns 2 links unpaginated but only 1 through combined-link cursors. Please fix those existing threads before merging. Also update the native SQL test expectation for the intentional hybrid weighting change: the current tests still require 2/61 where the new 0.55/0.45 weighting produces 1/61. There are two new plugin-owned tables (initialized outside Server 000) and current merge conflicts; no approval.
|
The affected modules are Knowledge base. @Zxf-xufeng, please coordinate follow-up. Knowledge base: @Zxf-xufeng @Alanxtl. Please coordinate the review of the affected changes. |
hidb4ai
left a comment
There was a problem hiding this comment.
Reviewed ba5e160. The three existing parser/pagination findings remain reproducible; current evidence is in replies on their original threads. Real authenticated Server + spawned Worker + local BGE inference covered upload/import, hybrid retrieval, outline/section reads and Core context preparation, and reproduced both tree and link pagination loss. The knowledge-base suite passes 32 tests with 8 opt-in skips. Real isolated OceanBase new/legacy/interrupted-index-upgrade cases all reach the hybrid-score assertion and fail because the test still expects 2/61 after the fusion weights changed; they are not passing acceptance. All three isolated databases were dropped. Two actual plugin tables are added; RFC 2570 assigns their migration to plugin storage rather than the Server 000 chain. Master integration conflicts in content.py and service.py. CI checkout transport failures and skipped downstream checks do not establish merge readiness. Merge score: 35/100; changes requested.
ba5e160 to
eb0a354
Compare
Which issue or RFC does this PR close?
Related to RFC #2570 (
knowledge-baseplugin).Rationale for this change
In structured Markdown knowledge bases (thousands of similar documents with tables and relative links) as well as row-oriented tabular operational records, baseline chunking and hybrid retrieval had several limitations:
## Sectionseparated from a large table) and missing document/section context in indexed text degraded recall.What changes are included in this PR?
content.py,models.py):section_keyidentifiers.TableBlockchunker supportingtable_row_mode(packedandper_row), header inheritance across slices, key-anchored splitting of oversized single rows withrow_id/part_index/part_total/synthetic_prefixprovenance, and configurablemax_chunks_per_doc(up to 20,000).display_textfrom context-enrichedindex_text(with bounded prefix budget to preserveno_truncation()safety) and added deterministicindex_text_hash.store.py):result_id-bound tables:pc_knowledge_base_doc_indexandpc_knowledge_base_links(preserving RFC 2570(scope_id, collection_id, relative_path)document identity and OceanBase/MySQLutf8mb43072-byte index key limits).jiebawith 14-char pure[a-z0-9]short-hash identifier tokens (id<sha256[:12]>) and a selectivity-guarded exact-identifier retrieval channel.(embedding_profile, index_text_hash)across revisions.service.py,plugin.py):POST /retrieveandPOST /scopes/{scope_id}/retrievewith backward-compatible options:path_prefix,collection_id,expand_section(disabled forper_row),expand_links(0/1),include_outline, and per-identifier 4-stateidentifier_signals(resolved_object,text_mention_only,not_found,unverified).mode="fts"skips embedding calls) and updatedupdate_artifactto clear stale snapshot line locators on edited chunks and recomputedoc_index/links.expand_sectionto Coresearch_artifacts./v1/plugins/knowledge-base/api:GET /scopes/{scope_id}/treeGET /scopes/{scope_id}/documents/{document_id}/outline?revision=GET /scopes/{scope_id}/documents/{document_id}/revisions/{revision}/sectionsGET /scopes/{scope_id}/documents/{document_id}/revisions/{revision}/linkstests/knowledge_base/test_retrieval_optimization.py):per_rowmode, FTS5 short-hash collision prevention,collection_idlink isolation, 4-stateidentifier_signals, offline FTS, and incremental vector reuse.Are there any user-facing changes?
Chunking,Retrieve, and four new read-only plugin API endpoints listed above.pc_knowledge_base_doc_indexandpc_knowledge_base_links) created automatically duringStore.initialize(). Existing pre-upgraderesult_idrevisions continue to work via fallback retrieval until reprocessed.How was this change tested?
uv run prek run --files plugins/knowledge-base/pc_knowledge_base/models.py plugins/knowledge-base/pc_knowledge_base/content.py plugins/knowledge-base/pc_knowledge_base/store.py plugins/knowledge-base/pc_knowledge_base/service.py plugins/knowledge-base/plugin.py tests/knowledge_base/test_retrieval_optimization.py(all hooks includingruff check,ruff format, andty checkpassed).uv run pytest tests/knowledge_base/ -q(30 passed, 10 skipped).not_foundaccurately reported for nonexistent table identifiers.per_rowoperational table: 10/10 Top-5 case recall withoutexpand_sectionexplosion, and 100% vector cache reuse for unchanged rows when appending 100 new rows.bge-small-zh-v1.5model inference were not executed in this local run.AI usage statement
Built with Antigravity (Gemini 4 Neon) for design review, implementation, and unit/benchmark test authoring; all code and checks were reviewed and verified locally.