Repository navigation
Feat: compiled knowledge pages as optional retrieval layer (#14089) - #14098
wdeveloper16 wants to merge 8 commits into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramssequenceDiagram
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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 forcontent_ltksand again insidefine_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_sizeis 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] * 1024vectors which may not match the actual embedding dimensions used elsewhere.Consider using
sres.query_vectorlength as the default, similar to theretrieval()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.insertcall 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
📒 Files selected for processing (11)
api/apps/chunk_app.pyapi/apps/kb_app.pyapi/db/__init__.pyapi/db/db_models.pyapi/db/services/dialog_service.pyapi/db/services/document_service.pyapi/db/services/pipeline_operation_log_service.pycommon/constants.pyrag/compiled_pages.pyrag/nlp/search.pyrag/svr/task_executor.py
…cture, doc_ids scoping
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
rag/compiled_pages.py (4)
198-204: Minor note:"id"in fields list is redundant.The
chunk_listmethod (per context snippet 1) adds the"id"field from the dictionary key after retrieval, so including it in thefieldsparameter 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_tokensAs 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_timestring andcreate_timestamp_fltare generated from separatedatetime.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 > 0but thererank()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
📒 Files selected for processing (5)
api/apps/chunk_app.pyapi/db/__init__.pyapi/db/services/dialog_service.pyrag/compiled_pages.pyrag/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
|
Hi, @ZhenhangTung |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
api/apps/chunk_app.py (1)
526-535:⚠️ Potential issue | 🟠 MajorPreserve doc-scoped mode when filters resolve to zero documents.
retrieval_compiled_pages()is intentionally skipped for doc-scoped retrieval, but Line 535 collapses[]toNone. 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.warningcalls 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
📒 Files selected for processing (6)
api/apps/chunk_app.pyapi/db/db_models.pyapi/db/services/dialog_service.pyapi/db/services/pipeline_operation_log_service.pyrag/nlp/search.pyrag/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
|
Hi, maintainers! |
|
Hi, @yingfeng |
|
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. |
|
Hi, @yingfeng |
|
@yingfeng Thanks for the clarification. |
|
It's under design |
No, problem at all. |
Has not been decided,yet. Say https://arxiv.org/abs/2604.14572 could be some kind of reference design |
|
Close this PR because it is not truly the goal of the original feature request. |
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 withcompiled_page_kwd,compiled_page_type_kwd, andsource_chunk_ids_kwd(for citation tracing)common/constants.py/api/db/__init__.py—PipelineTaskType.COMPILED_PAGES = "CompiledPages"added to enum,VALID_PIPELINE_TASK_TYPES, andPIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPESapi/db/db_models.py—compiled_page_task_id+compiled_page_task_finish_atonKnowledgebase; DB migration;use_compiled_pages: falsedefault in search configapi/db/services/document_service.py—queue_raptor_o_graphrag_tasksaccepts"compiled_pages"task typeapi/db/services/pipeline_operation_log_service.py— recordscompiled_page_task_finish_aton completionrag/svr/task_executor.py— routes"compiled_pages"task type, callsbuild_compiled_pages, inserts pages into doc storeapi/apps/kb_app.py—POST /run_compiled_pages,GET /trace_compiled_pages, extendedDELETE /unbind_taskrag/nlp/search.py—Dealer.retrieval_compiled_pages()(hybrid search scoped to compiled pages only);compiled_page_kwdadded toget_filtersand defaultsrcfieldsapi/db/services/dialog_service.py—use_compiled_pagestoggle prepends compiled pages to retrieved chunksapi/apps/chunk_app.py— same toggle on the retrieval API endpointHow 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
faqpolicy_summaryentity_summarytopic_overviewTest plan
POST /run_compiled_pagestriggers task; task completes; compiled pages stored withcompiled_page_kwd=pageuse_compiled_pages: truereturns synthesised pages at top of context; citations trace back viasource_chunk_ids_kwd/retrieval) withuse_compiled_pages: trueworks correctlyDELETE /unbind_task?pipeline_task_type=CompiledPagesremoves all compiled pages and clearscompiled_page_task_idrun_compiled_pageswhile a task is already in progress returns an errorcompiled_page_task_id/compiled_page_task_finish_atcolumns cleanlyCloses #14089