Skip to content

feat(knowledge-base): improve structured chunking, indexing, and progressive retrieval - #2943

Closed
Zxf-xufeng wants to merge 0 commit into
masterfrom
feat/kb-retrieval-optimization
Closed

Zxf-xufeng wants to merge 0 commit into
masterfrom
feat/kb-retrieval-optimization

Conversation

@Zxf-xufeng

Copy link
Copy Markdown
Member

Which issue or RFC does this PR close?

Related to RFC #2570 (knowledge-base plugin).

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:

  • Standalone heading chunks (e.g., ## Section separated from a large table) and missing document/section context in indexed text degraded recall.
  • Naive character-based splitting broke Markdown table rows and dropped table headers on continuation slices.
  • Underscore/dotted identifiers were split by tokenizers and diluted across similar distractors, with no explicit identifier existence signals.
  • There was no intra-collection link graph or progressive disclosure endpoints for Agents to inspect outlines, read full sections, or follow explicit links.

What changes are included in this PR?

  • Structured Markdown & Row-Aware Table Chunking (content.py, models.py):
    • Eliminated standalone empty heading chunks when immediately followed by same-section content and assigned collision-free section_key identifiers.
    • Added a format-agnostic TableBlock chunker supporting table_row_mode (packed and per_row), header inheritance across slices, key-anchored splitting of oversized single rows with row_id / part_index / part_total / synthetic_prefix provenance, and configurable max_chunks_per_doc (up to 20,000).
    • Separated display_text from context-enriched index_text (with bounded prefix budget to preserve no_truncation() safety) and added deterministic index_text_hash.
  • Immutable Document & Link Index Tables + Dual-Track Retrieval (store.py):
    • Added two immutable result_id-bound tables: pc_knowledge_base_doc_index and pc_knowledge_base_links (preserving RFC 2570 (scope_id, collection_id, relative_path) document identity and OceanBase/MySQL utf8mb4 3072-byte index key limits).
    • Added dual-track tokenization combining jieba with 14-char pure [a-z0-9] short-hash identifier tokens (id<sha256[:12]>) and a selectivity-guarded exact-identifier retrieval channel.
    • Added chunk-level incremental vector reuse keyed by (embedding_profile, index_text_hash) across revisions.
  • Retrieval Extensions & Progressive Disclosure APIs (service.py, plugin.py):
    • Extended POST /retrieve and POST /scopes/{scope_id}/retrieve with backward-compatible options: path_prefix, collection_id, expand_section (disabled for per_row), expand_links (0/1), include_outline, and per-identifier 4-state identifier_signals (resolved_object, text_mention_only, not_found, unverified).
    • Preserved offline FTS availability (mode="fts" skips embedding calls) and updated update_artifact to clear stale snapshot line locators on edited chunks and recompute doc_index/links.
    • Automatically propagated improved indexing and bounded expand_section to Core search_artifacts.
    • Added four progressive read-only endpoints under /v1/plugins/knowledge-base/api:
      • GET /scopes/{scope_id}/tree
      • GET /scopes/{scope_id}/documents/{document_id}/outline?revision=
      • GET /scopes/{scope_id}/documents/{document_id}/revisions/{revision}/sections
      • GET /scopes/{scope_id}/documents/{document_id}/revisions/{revision}/links
  • Tests (tests/knowledge_base/test_retrieval_optimization.py):
    • Added focused unit and integration tests covering empty-heading elimination, table header inheritance, oversized row splitting, per_row mode, FTS5 short-hash collision prevention, collection_id link isolation, 4-state identifier_signals, offline FTS, and incremental vector reuse.

Are there any user-facing changes?

  • Additive, backward-compatible extensions to Chunking, Retrieve, and four new read-only plugin API endpoints listed above.
  • Two new additive plugin tables (pc_knowledge_base_doc_index and pc_knowledge_base_links) created automatically during Store.initialize(). Existing pre-upgrade result_id revisions continue to work via fallback retrieval until reprocessed.
  • No breaking changes to existing public APIs or persisted formats.

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 including ruff check, ruff format, and ty check passed).
  • uv run pytest tests/knowledge_base/ -q (30 passed, 10 skipped).
  • Local SQLite FTS5 stress benchmarks (with deterministic test vectors):
    • 2,000 structured Markdown documents (8,015 chunks, 999 high-similarity distractor pairs): single-shot retrieval reached 11/12 Top-5 and 12/12 Top-10 evidence completeness, with not_found accurately reported for nonexistent table identifiers.
    • 1,000-row per_row operational table: 10/10 Top-5 case recall without expand_section explosion, and 100% vector cache reuse for unchanged rows when appending 100 new rows.
  • Note: OceanBase / SeekDB live database execution and local ONNX bge-small-zh-v1.5 model 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.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +429 to +432
avail = max(32, maximum - len(anchor) - 4)
while len(seg) > avail:
segments.append(seg[:avail])
seg = f"{col_prefix}: {seg[avail:]}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 hidb4ai added the module:knowledge-base Primary module: knowledge base import, processing and retrieval label Dec 2, 2026

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@hireview001

Copy link
Copy Markdown
Collaborator

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.

@hireview001
hireview001 requested a review from Alanxtl December 2, 2026 18:37

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Zxf-xufeng Zxf-xufeng closed this Dec 4, 2026
@Zxf-xufeng
Zxf-xufeng force-pushed the feat/kb-retrieval-optimization branch from ba5e160 to eb0a354 Compare December 4, 2026 10:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:knowledge-base Primary module: knowledge base import, processing and retrieval

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants