Repository navigation
Feat: add wiki folder - #16749
Feat: add wiki folder#16749
Conversation
📝 WalkthroughWalkthroughThis PR extracts shared structure-compilation logic into a runner and new flow component, removes extractor-side compilation, adds wiki topic planning/persistence, and exposes topic filtering and listing through the dataset wiki API. ChangesStructure-compilation runner and consumers
Estimated code review effort: 4 (Complex) | ~60 minutes Wiki topic extraction and persistence
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Compiler as Compiler component
participant Runner as run_structure_compile_over_batches
participant Wiki as wiki.py PLAN/REFINE
participant ES as Elasticsearch
Compiler->>Runner: stream chunk batches per template
Runner->>Runner: compile_structure_from_text and merge
Runner->>Wiki: PLAN then REFINE when synthesis is enabled
Wiki-->>Runner: pages including topic
Runner->>ES: persist artifact_page rows with topic_kwd
Runner->>ES: ensure artifact_page_topic rows exist
Runner-->>Compiler: per-template aggregates
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/dataset_wiki_generator.py (2)
200-201: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd success logging for the topic-row insert flow.
_ensure_wiki_topic_rowsonly logs on the existence-read failure path; the insert branch is silent. Alogging.inforecording how many topic rows were inserted (vs. already-present) makes this new persistence flow observable and consistent with the surroundingwiki_persistlogging.As per coding guidelines: "Add logging for new flows".
📝 Proposed logging
if rows: await thread_pool_exec(settings.docStoreConn.insert, rows, index, ctx.kb_id) + logging.info( + "wiki_persist: inserted %d new artifact_page_topic row(s) for kb=%s (existing=%d)", + len(rows), + kb_id_str, + len(existing), + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py` around lines 200 - 201, The topic-row insert path in _ensure_wiki_topic_rows is silent, so add an info log in the rows-insert branch around thread_pool_exec(settings.docStoreConn.insert, rows, index, ctx.kb_id) that records how many topic rows were inserted and how many were already present; keep the message consistent with the existing wiki_persist logging and use _ensure_wiki_topic_rows as the anchor for the new success log.Source: Coding guidelines
310-310: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider
zip(..., strict=True).Ruff flags the implicit-length
zip. Lengths are already guaranteed equal by then_emb != len(pages)guard above, sostrict=Truejust documents that invariant and future-proofs against silent truncation.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py` at line 310, The loop in dataset_wiki_generator that iterates with zip(pages, embeddings) should make the equal-length assumption explicit. Update the zip usage in the page/embedding iteration to use strict=True, since the n_emb != len(pages) guard already guarantees matching lengths and this documents the invariant in the relevant generator function.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 291-327: The synthesis branch in
run_structure_compile_over_batches captures pages from wiki_refine_from_plan()
but never persists them, so the generated wiki pages are lost. After the
compile_kwd rewrite, either pass the pages into the existing ES
write/persistence path in this function or return them to the caller that
handles persistence; use the run_structure_compile_over_batches and
wiki_refine_from_plan symbols to locate the flow.
- Around line 305-326: The broad exception handler in the synthesis flow will
catch TaskCanceledException and prevent cancellation from propagating. In the
runner logic around wiki_refine_from_plan and the subsequent progress_cb
updates, add a dedicated except TaskCanceledException block before the generic
except Exception and re-raise it unchanged, so cancellation still exits the loop
while other synthesis errors continue to be logged with logging.exception.
In `@rag/flow/compiler/compiler.py`:
- Around line 87-89: The chunk ID generation in the compiler uses direct access
to ck["text"], which can crash for chunks that only carry content_with_weight or
have a missing/None text field. Update the chunk processing logic in the
compiler’s chunk loop to use the same safe fallback strategy as the runner,
preferring content_with_weight and then text, and only hashing a guaranteed
string value. Keep the doc_id assignment and xxhash-based id generation in that
path, but make the input retrieval robust so upstream chunk variants don’t raise
KeyError or TypeError.
- Around line 163-174: The call to run_structure_compile_over_batches in
compiler.py is hardcoding the language as "en", which breaks multilingual
document handling. Update the compiler flow to pass through the document’s
actual language value from the surrounding context or task input, matching the
task-executor path that already uses ctx.language, and keep the parameter wiring
consistent in Compiler/_compile so the locale is preserved end to end.
---
Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 200-201: The topic-row insert path in _ensure_wiki_topic_rows is
silent, so add an info log in the rows-insert branch around
thread_pool_exec(settings.docStoreConn.insert, rows, index, ctx.kb_id) that
records how many topic rows were inserted and how many were already present;
keep the message consistent with the existing wiki_persist logging and use
_ensure_wiki_topic_rows as the anchor for the new success log.
- Line 310: The loop in dataset_wiki_generator that iterates with zip(pages,
embeddings) should make the equal-length assumption explicit. Update the zip
usage in the page/embedding iteration to use strict=True, since the n_emb !=
len(pages) guard already guarantees matching lengths and this documents the
invariant in the relevant generator function.
🪄 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: c42e92c0-17bc-4ffb-931e-847502b33061
📒 Files selected for processing (11)
api/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pyconf/infinity_mapping.jsonrag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/wiki.pyrag/flow/compiler/__init__.pyrag/flow/compiler/compiler.pyrag/flow/compiler/schema.pyrag/flow/extractor/extractor.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/svr/task_executor_refactor/dataset_wiki_generator.py
💤 Files with no reviewable changes (1)
- rag/flow/extractor/extractor.py
| try: | ||
| from rag.advanced_rag.knowlege_compile.wiki import ( | ||
| wiki_plan_from_reduction, | ||
| wiki_refine_from_plan, | ||
| ) | ||
|
|
||
| progress_cb(msg=f"Synthesis PLAN for template {template_id} (kind={compile_kwd}) ...") | ||
| plan = await wiki_plan_from_reduction( | ||
| chat_mdl=chat_mdl_by_tid[template_id], | ||
| embd_mdl=embedding_model, | ||
| tenant_id=tenant_id, | ||
| kb_id=kb_id, | ||
| callback=progress_cb, | ||
| ) | ||
| if cancel_check(): | ||
| raise TaskCanceledException("Task was cancelled after synthesis PLAN") | ||
|
|
||
| if not plan or not plan.get("pages"): | ||
| progress_cb(msg=f"Synthesis: no pages planned for template {template_id}.") | ||
| else: | ||
| progress_cb(msg=f"Synthesis REFINE for template {template_id} ({len(plan['pages'])} page(s)) ...") | ||
| pages = await wiki_refine_from_plan( | ||
| chat_mdl=chat_mdl_by_tid[template_id], | ||
| embd_mdl=embedding_model, | ||
| tenant_id=tenant_id, | ||
| kb_id=kb_id, | ||
| callback=progress_cb, | ||
| example=example, | ||
| ) | ||
| # Overwrite compile_kwd on every output page so the | ||
| # synthesis type is tracked correctly in ES. | ||
| for p in pages or []: | ||
| p["compile_kwd"] = compile_kwd | ||
| progress_cb(msg=f"Synthesis done: {len(pages or [])} {compile_kwd} page(s) written.") | ||
| except Exception: | ||
| logging.exception("synthesis: failed for template %s", template_id) | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check whether wiki_refine_from_plan persists pages internally or returns them for caller persistence
ast-grep outline rag/advanced_rag/knowlege_compile/wiki.py --match wiki_refine_from_plan --view expanded
# Search for persistence calls (ES upsert, doc_store, etc.) inside wiki_refine_from_plan
rg -n 'docStoreConn|upsert|insert|bulk|index|save|persist|store' --type py rag/advanced_rag/knowlege_compile/wiki.py -C 3Repository: infiniflow/ragflow
Length of output: 33385
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== runner.py outline =="
ast-grep outline rag/advanced_rag/knowlege_compile/runner.py --view expanded
echo
echo "== search for wiki page persistence hooks =="
rg -n 'persist_wiki_pages_to_es|_persist_wiki_pages_to_es|wiki_refine_from_plan|artifact_page|compile_kwd' rag/advanced_rag/knowlege_compile -C 3
echo
echo "== task handler definitions =="
fd -a 'task*.py' rag/advanced_rag/knowlege_compile common task 2>/dev/null || true
rg -n 'class TaskHandler|def _persist_wiki_pages_to_es|persist_wiki_pages_to_es' -S .Repository: infiniflow/ragflow
Length of output: 39825
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== dataset_wiki_generator outline =="
ast-grep outline rag/svr/task_executor_refactor/dataset_wiki_generator.py --view expanded
echo
echo "== task_handler outline =="
ast-grep outline rag/svr/task_executor_refactor/task_handler.py --view expanded
echo
echo "== persistence call site and helper =="
sed -n '180,240p' rag/svr/task_executor_refactor/dataset_wiki_generator.py
echo '---'
sed -n '860,920p' rag/svr/task_executor_refactor/dataset_wiki_generator.py
echo '---'
rg -n '_persist_wiki_pages_to_es|persist_wiki_pages_to_es|wiki pages' rag/svr/task_executor_refactor/task_handler.py -C 4Repository: infiniflow/ragflow
Length of output: 5826
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== runner.py excerpt =="
sed -n '240,360p' rag/advanced_rag/knowlege_compile/runner.py
echo
echo "== callers of run_structure_compile_over_batches =="
rg -n 'run_structure_compile_over_batches\(' -S .Repository: infiniflow/ragflow
Length of output: 4810
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '130,190p' rag/flow/compiler/compiler.py
echo '---'
sed -n '940,1010p' rag/svr/task_executor_refactor/chunk_post_processor.pyRepository: infiniflow/ragflow
Length of output: 4261
Persist synthesized wiki pages before returning
run_structure_compile_over_batches() drops the pages from wiki_refine_from_plan() after only rewriting compile_kwd. Wire these pages into the ES persistence path here, or return them to a caller that persists them; otherwise this synthesis branch never writes the generated pages.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/knowlege_compile/runner.py` around lines 291 - 327, The
synthesis branch in run_structure_compile_over_batches captures pages from
wiki_refine_from_plan() but never persists them, so the generated wiki pages are
lost. After the compile_kwd rewrite, either pass the pages into the existing ES
write/persistence path in this function or return them to the caller that
handles persistence; use the run_structure_compile_over_batches and
wiki_refine_from_plan symbols to locate the flow.
| for ck in chunks: | ||
| ck["doc_id"] = doc_id | ||
| ck["id"] = xxhash.xxh64((ck["text"] + str(ck["doc_id"])).encode("utf-8")).hexdigest() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
ck["text"] direct access risks KeyError/TypeError for upstream chunks.
The chunk ID is hashed from ck["text"], but if an upstream node emits chunks with content_with_weight (or any key other than text), or if the value is None, this line crashes with KeyError or TypeError. The runner itself defensively handles both content_with_weight and text (line 236 in runner.py), so this inconsistency will surface as a runtime crash for valid upstream data.
🐛 Proposed fix: use safe access consistent with the runner
for ck in chunks:
ck["doc_id"] = doc_id
- ck["id"] = xxhash.xxh64((ck["text"] + str(ck["doc_id"])).encode("utf-8")).hexdigest()
+ text = ck.get("content_with_weight") or ck.get("text") or ""
+ ck["id"] = xxhash.xxh64((str(text) + str(ck["doc_id"])).encode("utf-8")).hexdigest()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for ck in chunks: | |
| ck["doc_id"] = doc_id | |
| ck["id"] = xxhash.xxh64((ck["text"] + str(ck["doc_id"])).encode("utf-8")).hexdigest() | |
| for ck in chunks: | |
| ck["doc_id"] = doc_id | |
| text = ck.get("content_with_weight") or ck.get("text") or "" | |
| ck["id"] = xxhash.xxh64((str(text) + str(ck["doc_id"])).encode("utf-8")).hexdigest() |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/flow/compiler/compiler.py` around lines 87 - 89, The chunk ID generation
in the compiler uses direct access to ck["text"], which can crash for chunks
that only carry content_with_weight or have a missing/None text field. Update
the chunk processing logic in the compiler’s chunk loop to use the same safe
fallback strategy as the runner, preferring content_with_weight and then text,
and only hashing a guaranteed string value. Keep the doc_id assignment and
xxhash-based id generation in that path, but make the input retrieval robust so
upstream chunk variants don’t raise KeyError or TypeError.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/svr/task_executor_refactor/dataflow_service.py`:
- Around line 112-119: The Pipeline initialization in the dataflow execution
path only records ctx.language and does not update the tokenizer’s active
language before chunk processing. In the flow that creates Pipeline and then
tokenizes chunks, call rag_tokenizer.tokenizer.set_language(ctx.language) before
_process_chunks() / rag_tokenizer.tokenize() so the tokenizer uses the current
task language instead of stale global state.
🪄 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: 3bddc04a-4d0d-4fe8-a0e9-f6bd13259310
📒 Files selected for processing (7)
api/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pyrag/advanced_rag/knowlege_compile/runner.pyrag/flow/compiler/compiler.pyrag/flow/pipeline.pyrag/svr/task_executor.pyrag/svr/task_executor_refactor/dataflow_service.py
🚧 Files skipped from review as they are similar to previous changes (2)
- rag/flow/compiler/compiler.py
- rag/advanced_rag/knowlege_compile/runner.py
| pipeline = Pipeline( | ||
| dsl, | ||
| tenant_id=ctx.tenant_id, | ||
| doc_id=doc_id, | ||
| task_id=task_id, | ||
| flow_id=dataflow_id, | ||
| language=ctx.language, | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Search for set_language calls in the refactored task executor code path.
# Check for set_language in the task_executor_refactor directory
rg -n -C3 'set_language' rag/svr/task_executor_refactor/
# Also check TaskContext initialization for language setup
rg -n -C3 'class TaskContext' rag/svr/task_executor_refactor/ --type=pythonRepository: infiniflow/ragflow
Length of output: 187
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate tokenizer language setup and tokenization in the refactored executor path.
rg -n -C3 'set_language|tokenize\(' rag/svr/task_executor_refactor/ rag/ | sed -n '1,220p'
# Find TaskContext definition and any language-related initialization.
rg -n -C3 'class TaskContext|language' rag/svr/task_executor_refactor/ | sed -n '1,220p'
# Show the relevant section of the target file.
sed -n '1,420p' rag/svr/task_executor_refactor/dataflow_service.pyRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find explicit language-setting calls for the tokenizer across the repo.
rg -n -C2 'set_language\(' rag/ api/ common/ | sed -n '1,220p'
# Inspect the tokenizer implementation for default language/state handling.
rg -n -C3 'class .*Tokenizer|def set_language|def tokenize|language' rag/nlp* rag/nlp/ | sed -n '1,260p'
# Inspect pipeline code for any language setup before dataflow chunk processing.
rg -n -C3 'language=|set_language|rag_tokenizer' rag/flow/ rag/svr/task_executor_refactor/ | sed -n '1,260p'Repository: infiniflow/ragflow
Length of output: 41102
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect pipeline language handling.
sed -n '1,220p' rag/flow/pipeline.py
# Inspect compiler language handling around the dataflow path.
sed -n '1,280p' rag/flow/compiler/compiler.py
# Inspect tokenizer flow for any implicit language setup or dependence on Pipeline.language.
sed -n '1,260p' rag/flow/tokenizer/tokenizer.pyRepository: infiniflow/ragflow
Length of output: 25017
Set rag_tokenizer language before chunk tokenization
Pipeline(..., language=ctx.language) only stores the value; _process_chunks() still calls rag_tokenizer.tokenize() against the tokenizer’s previous global language state. Set rag_tokenizer.tokenizer.set_language(ctx.language) in this path before tokenizing, or multilingual tasks can be indexed with stale tokens.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/svr/task_executor_refactor/dataflow_service.py` around lines 112 - 119,
The Pipeline initialization in the dataflow execution path only records
ctx.language and does not update the tokenizer’s active language before chunk
processing. In the flow that creates Pipeline and then tokenizes chunks, call
rag_tokenizer.tokenizer.set_language(ctx.language) before _process_chunks() /
rag_tokenizer.tokenize() so the tokenizer uses the current task language instead
of stale global state.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16749 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Add wiki folders.