Skip to content

Feat: compiled knowledge pages as optional retrieval layer (#14089) - #14098

Closed
wdeveloper16 wants to merge 8 commits into
infiniflow:mainfrom
wdeveloper16:feat/compiled-knowledge-pages
Closed

wdeveloper16 wants to merge 8 commits into
infiniflow:mainfrom
wdeveloper16:feat/compiled-knowledge-pages

Conversation

@wdeveloper16

Copy link
Copy Markdown
Contributor

Summary

Implements the feature requested in #14089 — an optional Compiled Knowledge Pages layer that sits between raw document chunks and the LLM response.

Instead of returning scattered chunks from multiple documents, this feature adds an offline compilation step that uses an LLM to synthesise those chunks into coherent, wiki-style "knowledge pages" (topic overviews, FAQ pages, entity summaries, policy summaries). These pages are stored as a separately retrievable layer and can be toggled on per chat session.

The implementation follows the exact same architectural pattern as the existing GraphRAG and RAPTOR optional layers.

Changes

  • rag/compiled_pages.py (new) — compilation engine: groups chunks into token-bounded sections per document, calls LLM to synthesise each section into a typed knowledge page, embeds and stores the result with compiled_page_kwd, compiled_page_type_kwd, and source_chunk_ids_kwd (for citation tracing)
  • common/constants.py / api/db/__init__.py — PipelineTaskType.COMPILED_PAGES = "CompiledPages" added to enum, VALID_PIPELINE_TASK_TYPES, and PIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPES
  • api/db/db_models.py — compiled_page_task_id + compiled_page_task_finish_at on Knowledgebase; DB migration; use_compiled_pages: false default in search config
  • api/db/services/document_service.py — queue_raptor_o_graphrag_tasks accepts "compiled_pages" task type
  • api/db/services/pipeline_operation_log_service.py — records compiled_page_task_finish_at on completion
  • rag/svr/task_executor.py — routes "compiled_pages" task type, calls build_compiled_pages, inserts pages into doc store
  • api/apps/kb_app.py — POST /run_compiled_pages, GET /trace_compiled_pages, extended DELETE /unbind_task
  • rag/nlp/search.py — Dealer.retrieval_compiled_pages() (hybrid search scoped to compiled pages only); compiled_page_kwd added to get_filters and default src fields
  • api/db/services/dialog_service.py — use_compiled_pages toggle prepends compiled pages to retrieved chunks
  • api/apps/chunk_app.py — same toggle on the retrieval API endpoint

How it works

POST /run_compiled_pages → task_executor dispatches "compiled_pages" → build_compiled_pages(): chunks → section groups → LLM synthesis → embed → store → stored with: compiled_page_kwd="page", compiled_page_type_kwd, source_chunk_ids_kwd
Chat: use_compiled_pages=true → retrieval_compiled_pages() → pages prepended to chunks

Page types detected automatically

Type Signals
faq Q:/A: patterns, "frequently asked"
policy_summary "policy", "must", "shall", "compliance"
entity_summary "is a", "refers to", "definition", "concept"
topic_overview fallback

Test plan

  • POST /run_compiled_pages triggers task; task completes; compiled pages stored with compiled_page_kwd=page
  • Chat with use_compiled_pages: true returns synthesised pages at top of context; citations trace back via source_chunk_ids_kwd
  • Retrieval API (/retrieval) with use_compiled_pages: true works correctly
  • DELETE /unbind_task?pipeline_task_type=CompiledPages removes all compiled pages and clears compiled_page_task_id
  • Running run_compiled_pages while a task is already in progress returns an error
  • DB migration adds compiled_page_task_id / compiled_page_task_finish_at columns cleanly

Closes #14089

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Apr 14, 2026
@coderabbitai

coderabbitai Bot commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a compiled-pages pipeline and retrieval layer: generate synthesized knowledge pages from chunks, index them with embeddings/metadata, expose task run/trace endpoints, integrate compiled-page retrieval into chat/dialog flows, extend task enums/KB model fields, and wire executor/queue to produce and index pages.

Changes

Cohort / File(s) Summary
Compiled Pages Core
rag/compiled_pages.py
New module: build_compiled_pages(...) synthesizes token-bounded pages from chunks, classifies page types, embeds text, builds deterministic IDs and metadata fields (compiled_page_kwd, compiled_page_type_kwd, source_chunk_ids_kwd), supports cancellation, fallbacks, and progress callbacks.
Search / Retrieval Layer
rag/nlp/search.py
Added Dealer.retrieval_compiled_pages(...); extended Dealer.get_filters and default src to include compiled-page fields; vector-search + rerank, map hits to chunk-shaped dicts filtered by similarity threshold.
Task Execution & Queue
rag/svr/task_executor.py, api/db/services/document_service.py
Mapped "compiled_pages" task type to PipelineTaskType.COMPILED_PAGES; added handler branch to build pages (LLM + embed bundles), index produced pages into doc store; allowed ty="compiled_pages" when enqueuing tasks.
API Endpoints & KB Model
api/apps/kb_app.py, api/db/db_models.py
Added POST /run_compiled_pages and GET /trace_compiled_pages; KB model new fields compiled_page_task_id, compiled_page_task_finish_at; DB migration adds corresponding columns; task cancellation extended to handle compiled-pages and delete compiled-page docs.
Retrieval Integration
api/apps/chunk_app.py, api/db/services/dialog_service.py
Read use_compiled_pages flag from requests/config; when enabled and embedding bundle available, call retrieval_compiled_pages(...) and prepend compiled-page chunks to retrieval lists before downstream ranking/prompting.
Pipeline Logging & Timestamps
api/db/services/pipeline_operation_log_service.py
Operation-log path expanded to include PipelineTaskType.COMPILED_PAGES and update Knowledgebase.compiled_page_task_finish_at when task finishes.
Constants & Validation
api/db/__init__.py, common/constants.py
Added PipelineTaskType.COMPILED_PAGES = "CompiledPages"; included in VALID_PIPELINE_TASK_TYPES and special freeze list.
Dialog/Document Services
api/db/services/dialog_service.py, api/db/services/document_service.py
Dialog retrieval optionally prepends compiled pages into kbinfos["chunks"]; queue_raptor_o_graphrag_tasks assertion now allows ty="compiled_pages".

Sequence Diagrams

sequenceDiagram
    participant User
    participant API as API (kb_app)
    participant DB as Database
    participant Queue as TaskQueue
    participant Executor as TaskExecutor
    participant KB as KnowledgeBase
    participant LLM as LLM
    participant Embed as Embedder
    participant DocStore as DocStore

    User->>API: POST /run_compiled_pages (kb_id)
    API->>DB: Load KB, check compiled_page_task_id
    API->>Queue: Enqueue task ty="compiled_pages"
    Queue-->>API: Return task_id
    API->>DB: Save compiled_page_task_id
    API-->>User: Return task_id

    Queue->>Executor: Start compiled_pages task
    Executor->>KB: Load KB & parser_config
    Executor->>LLM: Create chat bundle
    Executor->>Embed: Create embedding bundle

    loop per document
      Executor->>Executor: Fetch chunks, group into sections
      loop per section
        Executor->>LLM: Synthesize page text
        LLM-->>Executor: Synthesized text
        Executor->>Embed: Embed text
        Embed-->>Executor: Vector
        Executor->>Executor: Build page record (id, metadata)
      end
    end

    Executor->>DocStore: Index compiled pages (compiled_page_kwd="page")
    Executor->>DB: Update compiled_page_task_finish_at
Loading
sequenceDiagram
    participant User
    participant Chat as Chat/API
    participant Retriever as Retriever
    participant Search as SearchService
    participant Reranker as Reranker
    participant DocStore as DocStore
    participant LLM as LLM

    User->>Chat: Send message (use_compiled_pages=true)
    Chat->>Retriever: Retrieve knowledge for question

    Retriever->>Search: retrieval_compiled_pages(question,...)
    Search->>DocStore: Query compiled pages (compiled_page_kwd="page")
    DocStore-->>Search: Compiled page hits
    Search->>Reranker: Re-rank using vectors + weight
    Reranker-->>Search: Top results
    Search-->>Retriever: Compiled pages (chunk-shaped)
    Retriever->>Retriever: Prepend compiled pages to chunk list

    Chat->>LLM: Generate response using compiled pages + chunks
    LLM-->>Chat: Response with citations
    Chat-->>User: Final answer
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Suggested labels

size:XXL

Poem

🐰 I nibbled chunks and stitched a page,
Sprinkled prompts and hopped on stage.
FAQs and summaries in tidy rows,
Hopped through docs where knowledge grows.
Now answers bound, with cited toes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Feat: compiled knowledge pages as optional retrieval layer (#14089)' accurately and concisely summarizes the main addition: a new optional retrieval layer for compiled knowledge pages, matching the PR's primary change.
Description check ✅ Passed The PR description comprehensively covers the problem statement, implementation details across all modified files, how the feature works end-to-end, and includes a detailed test plan. It closely aligns with the repository's template by providing context and problem statement.
Linked Issues check ✅ Passed The PR fully implements the coding objectives from issue #14089: compiled pages as an optional retrieval layer with LLM synthesis, source traceability via metadata fields, integration into existing retrieval patterns, optional toggles per chat session, and storage as a separate layer.
Out of Scope Changes check ✅ Passed All code changes are directly scoped to implementing compiled knowledge pages: new compilation engine, database schema updates, task routing, API endpoints, and retrieval integration. No unrelated refactoring or auxiliary changes are present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 💞 feature Feature request, pull request that fullfill a new feature. labels Apr 14, 2026

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 4

🧹 Nitpick comments (3)
rag/compiled_pages.py (1)

261-264: Minor inefficiency: tokenization called twice.

rag_tokenizer.tokenize(synthesised) is called twice — once for content_ltks and again inside fine_grained_tokenize. Consider reusing the result.

♻️ Suggested fix
+            content_ltks = rag_tokenizer.tokenize(synthesised)
             d = {
                 "id": chunk_id,
                 "doc_id": fake_doc_id,
                 "kb_id": [kb_id],
                 "docnm_kwd": page_title,
                 "title_tks": rag_tokenizer.tokenize(page_title),
                 "content_with_weight": synthesised,
-                "content_ltks": rag_tokenizer.tokenize(synthesised),
-                "content_sm_ltks": rag_tokenizer.fine_grained_tokenize(
-                    rag_tokenizer.tokenize(synthesised)
-                ),
+                "content_ltks": content_ltks,
+                "content_sm_ltks": rag_tokenizer.fine_grained_tokenize(content_ltks),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/compiled_pages.py` around lines 261 - 264, The code currently calls
rag_tokenizer.tokenize(synthesised) twice for "content_ltks" and inside
rag_tokenizer.fine_grained_tokenize; compute tokens once (e.g., tokens =
rag_tokenizer.tokenize(synthesised)) and reuse that variable when setting
"content_ltks" and when calling rag_tokenizer.fine_grained_tokenize(tokens) to
avoid redundant work and improve performance; update the dict construction that
sets "content_ltks" and "content_sm_ltks" accordingly (references: synthensised
variable name "synthesised", rag_tokenizer.tokenize,
rag_tokenizer.fine_grained_tokenize, keys "content_ltks" and "content_sm_ltks").
rag/nlp/search.py (1)

774-805: Hardcoded vector_size may cause issues if embedding dimensions differ.

The vector_size is initialized to 1024 (line 775) and only updated when a vector field is found. If no vector field is found in any result, all chunks will have [0.0] * 1024 vectors which may not match the actual embedding dimensions used elsewhere.

Consider using sres.query_vector length as the default, similar to the retrieval() method (line 466-468).

♻️ Suggested fix
         chunks = []
-        vector_size = 1024
+        vector_size = len(sres.query_vector) if sres.query_vector else 1024
         for i, cid in enumerate(sres.ids):
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/nlp/search.py` around lines 774 - 805, The code hardcodes
vector_size=1024 causing incorrect zero vectors if no _vec fields appear;
instead initialize vector_size from the actual query embedding length (use
len(sres.query_vector) if present) before building chunks, and use that value
for the default d["vector"] (and still update vector_size when you detect a
field ending with "_vec" inside the loop). Update the initialization of
vector_size and ensure the loop that assigns d["vector"] uses [0.0]*vector_size
so defaults match actual embedding dimensions; reference sres.query_vector, the
local variable vector_size, the chunks list, and the loop that checks
fld.items() for keys ending with "_vec".
rag/svr/task_executor.py (1)

1130-1180: Add logging and error handling for the compiled pages task.

The handler lacks explicit logging compared to other similar handlers (e.g., graphrag at line 1123 logs task results). Additionally, the docStoreConn.insert call doesn't check for errors.

♻️ Suggested improvements
         async with kg_limiter:
             pages, token_count = await build_compiled_pages(
                 row=task,
                 doc_ids=task.get("doc_ids", []),
                 chat_mdl=chat_model,
                 embd_mdl=embedding_model,
                 vector_size=vector_size,
                 callback=progress_callback,
                 task_id=task_id,
                 max_section_tokens=max_section_tokens,
             )

         if pages:
-            await thread_pool_exec(
+            doc_store_result = await thread_pool_exec(
                 settings.docStoreConn.insert,
                 pages,
                 search.index_name(task_tenant_id),
                 task_dataset_id,
             )
+            if doc_store_result:
+                error_message = f"Insert compiled pages error: {doc_store_result}"
+                progress_callback(-1, error_message)
+                logging.error(error_message)
+                return

+        logging.info(f"CompiledPages task completed for kb {task_dataset_id}: {len(pages)} pages, {token_count} tokens, elapsed: {timer() - start_ts:.2f}s")
         progress_callback(prog=1.0, msg="Compiled Pages done ({:.2f}s), {} pages built".format(timer() - start_ts, len(pages)))

As per coding guidelines: "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/svr/task_executor.py` around lines 1130 - 1180, The compiled_pages branch
lacks logging and error handling: add structured logging (info/debug) at key
points in the flow (start of task with task_id/task_dataset_id/task_tenant_id,
after build_compiled_pages with token_count, number of pages and duration, and
before/after the insert) and ensure exceptions are handled—wrap the call to
build_compiled_pages and the thread_pool_exec(settings.docStoreConn.insert, ...)
in try/except blocks, log errors via logger.error including
task_id/task_dataset_id and the caught exception, and call
progress_callback(prog=-1.0, msg=...) on failure; also validate the return value
of Settings.docStoreConn.insert (or the result of thread_pool_exec) and treat
non-success as an error path using KnowledgebaseService.update_by_id,
build_compiled_pages, thread_pool_exec, settings.docStoreConn.insert, LLMBundle
and progress_callback as reference points to locate where to add these checks
and logs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/chunk_app.py`:
- Around line 517-529: The compiled-pages branch (when use_compiled_pages is
true) calls settings.retriever.retrieval_compiled_pages without applying the
request-scoped local_doc_ids/doc filter, so compiled_chunks can include docs
outside the requested metadata/doc_id scope and later get mixed into
ranks["chunks"]; update the code path around use_compiled_pages to pass the same
local_doc_ids (or equivalent doc_id filter) into retrieval_compiled_pages
(and/or filter compiled_chunks by local_doc_ids immediately after retrieval) and
then call retrieval_by_children, and add a debug/info log entry using
process/logger indicating that compiled-pages retrieval ran and how many
compiled_chunks were returned and whether any were filtered by local_doc_ids;
reference functions/variables: use_compiled_pages, retrieval_compiled_pages,
local_doc_ids, compiled_chunks, ranks["chunks"], retrieval_by_children, and
settings.retriever for locating the changes.

In `@api/db/__init__.py`:
- Line 74: The freeze set currently contains a wrong token for compiled pages
because PipelineTaskType.COMPILED_PAGES is being lower-cased incorrectly; update
PIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPES so it uses the enum's actual value
or the correct string (e.g. PipelineTaskType.COMPILED_PAGES.value.lower() or the
literal "compiled_pages") instead of the current expression, ensuring the set
member matches task record strings and thus triggers freeze behavior.

In `@api/db/services/dialog_service.py`:
- Around line 643-655: The compiled-pages branch (guarded by
prompt_config.get("use_compiled_pages") and embd_mdl) ignores active doc scoping
(attachments/filtered doc_ids) and may retrieve from the full KB via
settings.retriever.retrieval_compiled_pages; update the logic in the block
around prompt_config/use_compiled_pages/embd_mdl so that if dialog.attachments
or filtered doc_ids are present you either pass those constraints into
retrieval_compiled_pages (preferably as a doc_ids or scope parameter) or skip
compiled-pages retrieval entirely, and add a processLogger.debug/info line
indicating whether compiled-pages retrieval was executed or skipped and why;
ensure you reference the same parameters used today (tenant_ids, dialog.kb_ids,
dialog.top_n, dialog.similarity_threshold, dialog.vector_similarity_weight) when
calling retrieval_compiled_pages so behavior remains consistent.

In `@rag/compiled_pages.py`:
- Around line 108-129: The async_chat call in _call_llm is passing the
synthesized content as the system/prompt parameter but not including it in the
messages history; fix this by calling chat_mdl.async_chat with a proper system
instruction (prompt) and a messages list that includes the actual content as a
user message (e.g., [{"role":"system","content":prompt},
{"role":"user","content": content + "\n\nWrite the knowledge page:"}] or
similar) so the content is part of the messages argument to chat_mdl.async_chat
rather than only the first positional parameter.

---

Nitpick comments:
In `@rag/compiled_pages.py`:
- Around line 261-264: The code currently calls
rag_tokenizer.tokenize(synthesised) twice for "content_ltks" and inside
rag_tokenizer.fine_grained_tokenize; compute tokens once (e.g., tokens =
rag_tokenizer.tokenize(synthesised)) and reuse that variable when setting
"content_ltks" and when calling rag_tokenizer.fine_grained_tokenize(tokens) to
avoid redundant work and improve performance; update the dict construction that
sets "content_ltks" and "content_sm_ltks" accordingly (references: synthensised
variable name "synthesised", rag_tokenizer.tokenize,
rag_tokenizer.fine_grained_tokenize, keys "content_ltks" and "content_sm_ltks").

In `@rag/nlp/search.py`:
- Around line 774-805: The code hardcodes vector_size=1024 causing incorrect
zero vectors if no _vec fields appear; instead initialize vector_size from the
actual query embedding length (use len(sres.query_vector) if present) before
building chunks, and use that value for the default d["vector"] (and still
update vector_size when you detect a field ending with "_vec" inside the loop).
Update the initialization of vector_size and ensure the loop that assigns
d["vector"] uses [0.0]*vector_size so defaults match actual embedding
dimensions; reference sres.query_vector, the local variable vector_size, the
chunks list, and the loop that checks fld.items() for keys ending with "_vec".

In `@rag/svr/task_executor.py`:
- Around line 1130-1180: The compiled_pages branch lacks logging and error
handling: add structured logging (info/debug) at key points in the flow (start
of task with task_id/task_dataset_id/task_tenant_id, after build_compiled_pages
with token_count, number of pages and duration, and before/after the insert) and
ensure exceptions are handled—wrap the call to build_compiled_pages and the
thread_pool_exec(settings.docStoreConn.insert, ...) in try/except blocks, log
errors via logger.error including task_id/task_dataset_id and the caught
exception, and call progress_callback(prog=-1.0, msg=...) on failure; also
validate the return value of Settings.docStoreConn.insert (or the result of
thread_pool_exec) and treat non-success as an error path using
KnowledgebaseService.update_by_id, build_compiled_pages, thread_pool_exec,
settings.docStoreConn.insert, LLMBundle and progress_callback as reference
points to locate where to add these checks and logs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d341e28e-7533-4ea0-ac94-5bc7d440d7ae

📥 Commits

Reviewing files that changed from the base of the PR and between c22811f and c435f52.

📒 Files selected for processing (11)
  • api/apps/chunk_app.py
  • api/apps/kb_app.py
  • api/db/__init__.py
  • api/db/db_models.py
  • api/db/services/dialog_service.py
  • api/db/services/document_service.py
  • api/db/services/pipeline_operation_log_service.py
  • common/constants.py
  • rag/compiled_pages.py
  • rag/nlp/search.py
  • rag/svr/task_executor.py

Comment thread api/apps/chunk_app.py Resolved
Comment thread api/db/__init__.py Resolved
Comment thread api/db/services/dialog_service.py Resolved
Comment thread rag/compiled_pages.py Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (5)
rag/compiled_pages.py (4)

198-204: Minor note: "id" in fields list is redundant.

The chunk_list method (per context snippet 1) adds the "id" field from the dictionary key after retrieval, so including it in the fields parameter is unnecessary (though harmless).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/compiled_pages.py` around lines 198 - 204, The fields list passed to
settings.retriever.chunk_list unnecessarily includes "id"; remove "id" from the
fields parameter in the call that builds chunks (the invocation using doc_id,
tenant_id, [kb_id], fields=["content_with_weight", "id"], sort_by_position=True)
so only "content_with_weight" is requested, since chunk_list already adds the id
from the dict key.

232-237: Consider logging summary of successful vs failed sections.

When embedding fails, the section is silently skipped. While individual failures are logged, there's no final summary indicating how many pages were successfully generated vs skipped. This could help with debugging and monitoring.

💡 Optional: Add summary logging
+    if results:
+        logging.info(f"CompiledPages: generated {len(results)} pages, consumed {total_tokens} tokens")
+    elif doc_ids:
+        logging.warning(f"CompiledPages: no pages generated for {len(doc_ids)} documents")
+
     return results, total_tokens

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/compiled_pages.py` around lines 232 - 237, Add counters to track
successful vs failed section embeddings around the embd_mdl.encode call:
increment a "success_count" when vts/vctr are produced (e.g., after vctr =
vts[0].tolist()) and increment a "failure_count" inside the except block where
logging.warning currently runs (use the existing doc_name and sec_idx for
context). After the loop that processes sections (or at the end of the function
that contains this code), emit a single summary log (logging.info) reporting
total sections processed, success_count and failure_count for that doc_name (or
overall), ensuring the new flows use the project's logging facility and follow
existing naming conventions.

173-174: Minor: No-op callback could be a lambda for brevity.

The default callback pattern is functional but could be simplified.

💡 Optional simplification
     if callback is None:
-        def callback(**_kw): pass
+        callback = lambda **_kw: None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/compiled_pages.py` around lines 173 - 174, Replace the no-op multi-line
function assigned to callback with a concise lambda: when callback is None set
callback = lambda **_kw: None; update the callback defaulting logic (the
variable named callback) in the same block so the behavior remains identical but
uses the shorter lambda form.

265-266: Minor: datetime.now() called twice creates potential timestamp mismatch.

The create_time string and create_timestamp_flt are generated from separate datetime.now() calls, which could differ by milliseconds if execution is slow.

🔧 Proposed fix
+            now = datetime.now()
             d = {
                 ...
-                "create_time": str(datetime.now()).replace("T", " ")[:19],
-                "create_timestamp_flt": datetime.now().timestamp(),
+                "create_time": str(now).replace("T", " ")[:19],
+                "create_timestamp_flt": now.timestamp(),
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/compiled_pages.py` around lines 265 - 266, The code calls datetime.now()
twice for "create_time" and "create_timestamp_flt" which can produce slightly
different timestamps; capture a single datetime once (e.g., assign
datetime.now() to a local variable) and then derive both "create_time" and
"create_timestamp_flt" from that single variable so "create_time" and
"create_timestamp_flt" remain consistent.
rag/nlp/search.py (1)

777-783: Consider handling empty rerank results.

If sres.total > 0 but the rerank() method returns empty arrays (e.g., due to missing embeddings), the subsequent loop won't execute, which is safe. However, this edge case could silently return an empty list when compiled pages exist but have corrupt/missing vector data.

💡 Optional: Add debug logging for this edge case
         sim, tsim, vsim = self.rerank(
             sres,
             question,
             1 - vector_similarity_weight,
             vector_similarity_weight,
             rank_feature=None,
         )
+        if not sim:
+            logging.debug("retrieval_compiled_pages: rerank returned empty scores for %d candidates", sres.total)
+            return []

         chunks = []
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/nlp/search.py` around lines 777 - 783, The rerank call (rerank returning
sim, tsim, vsim) can yield empty arrays even when sres.total > 0 (e.g.,
missing/corrupt embeddings), which silently results in an empty result list;
update the logic after the rerank call to detect this edge case (check if
sim/tsim/vsim are empty while sres.total > 0), log a warning that documents had
missing embeddings, and fall back to a safe behavior such as using the original
sres order or filtering out only the problematic documents before continuing
(reference rerank, sres.total, sim/tsim/vsim and the loop that consumes them) so
callers receive meaningful results instead of an empty list.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@rag/nlp/search.py`:
- Around line 791-810: The chunk dict built in retrieval_compiled_pages is
missing the tag_kwd field present in retrieval(), which can cause downstream
KeyError; update the dict (the one created as d with keys like "chunk_id",
"content_ltks", etc.) to include "tag_kwd": fld.get("tag_kwd", []) so
compiled-page output matches the standard schema and safely provides an empty
list when tags are absent.

---

Nitpick comments:
In `@rag/compiled_pages.py`:
- Around line 198-204: The fields list passed to settings.retriever.chunk_list
unnecessarily includes "id"; remove "id" from the fields parameter in the call
that builds chunks (the invocation using doc_id, tenant_id, [kb_id],
fields=["content_with_weight", "id"], sort_by_position=True) so only
"content_with_weight" is requested, since chunk_list already adds the id from
the dict key.
- Around line 232-237: Add counters to track successful vs failed section
embeddings around the embd_mdl.encode call: increment a "success_count" when
vts/vctr are produced (e.g., after vctr = vts[0].tolist()) and increment a
"failure_count" inside the except block where logging.warning currently runs
(use the existing doc_name and sec_idx for context). After the loop that
processes sections (or at the end of the function that contains this code), emit
a single summary log (logging.info) reporting total sections processed,
success_count and failure_count for that doc_name (or overall), ensuring the new
flows use the project's logging facility and follow existing naming conventions.
- Around line 173-174: Replace the no-op multi-line function assigned to
callback with a concise lambda: when callback is None set callback = lambda
**_kw: None; update the callback defaulting logic (the variable named callback)
in the same block so the behavior remains identical but uses the shorter lambda
form.
- Around line 265-266: The code calls datetime.now() twice for "create_time" and
"create_timestamp_flt" which can produce slightly different timestamps; capture
a single datetime once (e.g., assign datetime.now() to a local variable) and
then derive both "create_time" and "create_timestamp_flt" from that single
variable so "create_time" and "create_timestamp_flt" remain consistent.

In `@rag/nlp/search.py`:
- Around line 777-783: The rerank call (rerank returning sim, tsim, vsim) can
yield empty arrays even when sres.total > 0 (e.g., missing/corrupt embeddings),
which silently results in an empty result list; update the logic after the
rerank call to detect this edge case (check if sim/tsim/vsim are empty while
sres.total > 0), log a warning that documents had missing embeddings, and fall
back to a safe behavior such as using the original sres order or filtering out
only the problematic documents before continuing (reference rerank, sres.total,
sim/tsim/vsim and the loop that consumes them) so callers receive meaningful
results instead of an empty list.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 721b1357-b7a5-41e7-b8e1-784d2fb7ef57

📥 Commits

Reviewing files that changed from the base of the PR and between c435f52 and ea8baee.

📒 Files selected for processing (5)
  • api/apps/chunk_app.py
  • api/db/__init__.py
  • api/db/services/dialog_service.py
  • rag/compiled_pages.py
  • rag/nlp/search.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • api/db/init.py
  • api/db/services/dialog_service.py

Comment thread rag/nlp/search.py Resolved
@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @ZhenhangTung
Would you please review my first contribution?

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

♻️ Duplicate comments (1)
api/apps/chunk_app.py (1)

526-535: ⚠️ Potential issue | 🟠 Major

Preserve doc-scoped mode when filters resolve to zero documents.

retrieval_compiled_pages() is intentionally skipped for doc-scoped retrieval, but Line 535 collapses [] to None. If metadata/doc filters are active and narrow the scope to zero docs, this branch falls back to KB-wide compiled-page retrieval and can prepend unrelated pages into what should be an empty filtered result.

Proposed fix
+        doc_scope_active = bool(doc_ids) or bool(meta_data_filter)
+
-        if use_compiled_pages and embd_mdl:
+        if use_compiled_pages and embd_mdl and not doc_scope_active:
             compiled_chunks = await settings.retriever.retrieval_compiled_pages(
                 _question,
                 embd_mdl,
                 tenant_ids,
                 kb_ids,
                 page_size=size,
                 similarity_threshold=float(req.get("similarity_threshold", 0.2)),
                 vector_similarity_weight=float(req.get("vector_similarity_weight", 0.3)),
-                doc_ids=local_doc_ids or None,
+                doc_ids=None,
             )
             if compiled_chunks:
                 logging.debug(f"use_compiled_pages: prepending {len(compiled_chunks)} compiled page(s) to retrieval results")
                 ranks["chunks"] = compiled_chunks + ranks["chunks"]
+        elif use_compiled_pages and doc_scope_active:
+            logging.debug("use_compiled_pages: skipped because document/metadata scope is active")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/chunk_app.py` around lines 526 - 535, The bug is that when
doc-scoped filters resolve to zero documents we collapse local_doc_ids from []
to None which causes retrieval_compiled_pages(...) to run as KB-wide; update the
call in chunk_app.py so that the argument doc_ids passes local_doc_ids exactly
as-is (allowing an empty list) instead of converting falsy values to None,
ensuring retrieval_compiled_pages(...) receives [] when filters match zero docs
and thus preserves doc-scoped behavior.
🧹 Nitpick comments (1)
rag/svr/task_executor.py (1)

1170-1217: Add worker logs around the new compiled-pages flow.

This branch auto-enables config, builds pages, and writes to the doc store, but it only emits progress callbacks. A few logging.info/logging.warning calls around config mutation, build start, and inserted page count would make executor-side failures much easier to trace.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/svr/task_executor.py` around lines 1170 - 1217, Add executor-side logging
around the compiled_pages branch: log when you auto-enable the compiled_pages
config (include kb.id and the new parser_config) right before calling
KnowledgebaseService.update_by_id and log a warning/error if that update fails;
log an info message just before calling build_compiled_pages with task_id,
task_dataset_id and number of doc_ids to indicate build start; after
build_compiled_pages completes log the token_count and number of pages produced;
and after the thread_pool_exec insert call log the number of pages attempted to
insert and confirm success/failure (include references to
settings.docStoreConn.insert and search.index_name(task_tenant_id)). Ensure logs
use logging.info / logging.warning and include relevant identifiers (task_id,
task_tenant_id, kb.id).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@rag/svr/task_executor.py`:
- Around line 1209-1215: The current branch calls settings.docStoreConn.insert
via thread_pool_exec and ignores its return value (bypassing insert_chunks()),
which can cause reporting "Compiled Pages done" even when indexing failed;
capture the result of the await thread_pool_exec(...) call, check its truthiness
per the codebase convention (a truthy result indicates an indexing error), and
handle it the same way insert_chunks() does—log or raise the error and avoid
reporting success (e.g., propagate the error or return the failure) before
emitting the "Compiled Pages done" message; reference
settings.docStoreConn.insert, thread_pool_exec, and insert_chunks() when making
the change.
- Around line 1218-1219: The current assignment overwrites task_doc_id with the
first source doc id (fake_doc_ids := task.get("doc_ids", [])) which risks
deleting raw source chunks during cancellation; instead do not reassign
task_doc_id—introduce a new variable like source_doc_id = task["doc_ids"][0] (or
only read into source_doc_id) and leave task_doc_id as the synthesized/compiled
doc id used elsewhere, and update the cancellation/cleanup logic in the same
module to explicitly delete using the compiled doc id stored on the task (e.g.,
task.get("compiled_doc_id") or the original task_doc_id) so compiled-pages
deletions target compiled rows (see variable names task_doc_id, fake_doc_ids and
compiled_pages.py synthetic doc id handling).

---

Duplicate comments:
In `@api/apps/chunk_app.py`:
- Around line 526-535: The bug is that when doc-scoped filters resolve to zero
documents we collapse local_doc_ids from [] to None which causes
retrieval_compiled_pages(...) to run as KB-wide; update the call in chunk_app.py
so that the argument doc_ids passes local_doc_ids exactly as-is (allowing an
empty list) instead of converting falsy values to None, ensuring
retrieval_compiled_pages(...) receives [] when filters match zero docs and thus
preserves doc-scoped behavior.

---

Nitpick comments:
In `@rag/svr/task_executor.py`:
- Around line 1170-1217: Add executor-side logging around the compiled_pages
branch: log when you auto-enable the compiled_pages config (include kb.id and
the new parser_config) right before calling KnowledgebaseService.update_by_id
and log a warning/error if that update fails; log an info message just before
calling build_compiled_pages with task_id, task_dataset_id and number of doc_ids
to indicate build start; after build_compiled_pages completes log the
token_count and number of pages produced; and after the thread_pool_exec insert
call log the number of pages attempted to insert and confirm success/failure
(include references to settings.docStoreConn.insert and
search.index_name(task_tenant_id)). Ensure logs use logging.info /
logging.warning and include relevant identifiers (task_id, task_tenant_id,
kb.id).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 969aebd2-aa1b-4dc6-bff3-31ed33feea06

📥 Commits

Reviewing files that changed from the base of the PR and between 0a12f2a and 63b9a60.

📒 Files selected for processing (6)
  • api/apps/chunk_app.py
  • api/db/db_models.py
  • api/db/services/dialog_service.py
  • api/db/services/pipeline_operation_log_service.py
  • rag/nlp/search.py
  • rag/svr/task_executor.py
✅ Files skipped from review due to trivial changes (1)
  • api/db/db_models.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • api/db/services/pipeline_operation_log_service.py
  • api/db/services/dialog_service.py
  • rag/nlp/search.py

Comment thread rag/svr/task_executor.py Resolved
Comment thread rag/svr/task_executor.py Resolved
@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, maintainers!
Are there any guys to review this PR?

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
Would you please review the PR?

@yingfeng

Copy link
Copy Markdown
Member

This implementation is not what the feature request wanted. Actually, a compilation layer to combine Navi RAG together with LLM Wiki style is under our consideration and investigation.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
Thanks for your review.
Would you please clarify what you expected?

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

@yingfeng Thanks for the clarification.
I'd love to align with the intended direction , could you share more about the planned architecture combining Navi RAG and LLM Wiki style?
Even a rough design sketch or a linked issue would help me understand whether this PR can be reworked to fit that vision, or if it's better to close it and wait for the official design to land.

@yingfeng

Copy link
Copy Markdown
Member

It's under design

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

It's under design

No, problem at all.
Would you please provide me design?

@yingfeng

Copy link
Copy Markdown
Member

It's under design

No, problem at all. Would you please provide me design?

Has not been decided,yet. Say https://arxiv.org/abs/2604.14572 could be some kind of reference design

@yingfeng

yingfeng commented May 7, 2026

Copy link
Copy Markdown
Member

Close this PR because it is not truly the goal of the original feature request.

@yingfeng yingfeng closed this May 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Compiled knowledge pages as an optional retrieval layer

2 participants