Skip to content

Feat: Add knowledge compilation workflows - #16515

Merged
yingfeng merged 24 commits into
infiniflow:mainfrom
KevinHuSh:feat/knowledge_compilation_backend
Jul 2, 2026
Merged

yingfeng merged 24 commits into
infiniflow:mainfrom
KevinHuSh:feat/knowledge_compilation_backend

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

  • Add knowledge compilation template APIs, services, and builtin template seed data
  • Add advanced knowledge compile structure/artifact/RAPTOR workflow support
  • Update parsing, dataset/document APIs, and supporting services for compilation workflows

Validation

  • git diff --check
  • Python syntax compile for targeted backend/RAG files

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 1, 2026
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

This PR adds compilation-template/group management, structured knowledge compilation, artifact and skill dataset APIs, RAPTOR provenance/tree persistence, and a Redis-backed document chunking counter.

Changes

Compilation Template & Group System

Layer / File(s) Summary
Template and group models
api/db/db_models.py
Adds CompilationTemplate, CompilationTemplateGroup, ArtifactCommit models and new Knowledgebase task-tracking columns plus migration.
Template service and built-ins
api/db/services/compilation_template_service.py, api/db/init_data.py, api/db/init_data/compilation_templates/*.yaml
Adds CompilationTemplateService for CRUD, builtin loading/seeding, initialization wiring, and built-in YAML templates.
Template group service
api/db/services/compilation_template_group_service.py
Adds scope derivation, CRUD, resolution, and KB-oriented lookups for template groups.
Payload validation
api/apps/restful_apis/utils/compilation_template_validation.py
Validates template name/kind/config and nested artifact fields.
REST endpoints
api/apps/restful_apis/compilation_template_api.py, compilation_template_group_api.py
Adds builtin listing and group CRUD endpoints.
Parser config wiring
api/utils/validation_utils.py, api/apps/restful_apis/document_api.py
Normalizes compilation_template_group_id, triggers reparse on change.

Structure/Artifact/Skill Compilation Pipeline

Layer / File(s) Summary
Compilation core
rag/advanced_rag/knowlege_compile/_common.py, structure.py, __init__.py
Adds shared helpers, dedup engine, structure extraction/merge, and graph rebuild logic.
Dataset navigation
rag/advanced_rag/knowlege_compile/dataset_nav.py
Adds per-KB nav markdown upsert/removal guarded by a Redis lock.
Extractor wiring
rag/flow/extractor/extractor.py
Wires knowledge compilation into the extractor for set/list/graph fields.
Structure graph API & compiled-row exclusion
api/apps/restful_apis/chunk_api.py
Adds structure graph GET/DELETE endpoints and excludes compiled rows from chunk listing/retrieval/deletion.
Artifact/skill dataset API
api/apps/services/dataset_api_service.py, api/apps/restful_apis/dataset_api.py, api/db/services/document_service.py, api/db/services/artifact_commit_service.py, rag/nlp/search.py, rag/utils/es_conn.py
Adds artifact/skill existence, listing, graph browsing, page editing, and commit history endpoints/services, must_not filter support, and dataset nav pruning on doc removal.

RAPTOR Tree Mode and Provenance

Layer / File(s) Summary
RAPTOR provenance/clustering refactor
rag/advanced_rag/knowlege_compile/raptor.py
Adds source_chunk_ids provenance, title extraction, clustering, and tree-mode output.
Raptor service tree persistence
rag/svr/task_executor_refactor/raptor_service.py, rag/svr/task_executor_refactor/raptor_utils.py, rag/svr/task_executor.py, tests
Persists tree/graph rows, expands cleanup to both row types, updates import paths and test mocks.

Artifact/Skill Pipeline Task Type Plumbing

Layer / File(s) Summary
Task type constants and KB tracking
common/constants.py, api/db/__init__.py, api/db/services/knowledgebase_service.py, api/db/services/pipeline_operation_log_service.py
Adds ARTIFACT/SKILL task types, KB finish-time fields, and log/service updates.
Task executor routing
rag/svr/task_executor.py
Routes artifact/skill types, propagates doc ids, blocks legacy skill execution.

Chunking Progress Counter and Small Fixes

Layer / File(s) Summary
Redis chunking counter
api/db/services/task_service.py, rag/utils/redis_conn.py
Adds TTL-based pending counter for doc chunking with crediting/clearing.
Small fixes
api/db/services/dialog_service.py, rag/advanced_rag/knowlege_compile/mind_map_extractor.py, rag/prompts/generator.py
Adds intermediate streamed yield, removes stale comment, returns empty dict on exception.

Estimated code review effort: 5 (Critical) | ~110 minutes

Sequence Diagram(s)

sequenceDiagram
    participant Extractor
    participant StructureModule as structure.py
    participant EmbeddingModel
    participant ESStore as Doc Store
    participant LLM

    Extractor->>Extractor: sort chunks by page/top
    Extractor->>StructureModule: compile_structure_from_text(chunks, parser_config)
    StructureModule->>LLM: extract entities/relations per batch
    StructureModule->>EmbeddingModel: encode extracted payloads
    StructureModule-->>Extractor: ES-ready docs
    Extractor->>StructureModule: merge_compiled_structures(docs, tenant_id, kb_id)
    StructureModule->>StructureModule: local dedup (cosine similarity + LLM merge)
    StructureModule->>ESStore: KNN search for existing duplicates
    StructureModule->>LLM: duplicate verdict
    StructureModule->>ESStore: upsert merged/new rows
    StructureModule->>ESStore: rebuild structure graph JSON
    StructureModule-->>Extractor: merged result
Loading
sequenceDiagram
    participant Client
    participant DatasetAPI as dataset_api.py
    participant Service as dataset_api_service.py
    participant CommitService as ArtifactCommitService
    participant ESStore as Doc Store

    Client->>DatasetAPI: PUT /artifacts/{page_type}/{slug}
    DatasetAPI->>DatasetAPI: validate content_md/title/comments
    DatasetAPI->>Service: update_wiki_page(dataset_id, tenant_id, page_type, slug, content_md)
    Service->>ESStore: locate row id via search
    Service->>Service: transform markdown links, recompute summary/outlinks
    Service->>ESStore: partial update by id
    Service->>CommitService: record_edit(content_before, content_after)
    CommitService->>ESStore: insert ArtifactCommit row (diff, content_after)
    Service->>ESStore: get_wiki_page (fetch updated canonical page)
    Service-->>DatasetAPI: updated page
    DatasetAPI-->>Client: get_result(data=page)
Loading

Possibly related PRs

  • infiniflow/ragflow#15292: Touches the same chunk listing API path in api/apps/restful_apis/chunk_api.py, including page-size handling and related request validation.

Poem

A rabbit hops through templates new,
Compiling wikis, skills, and graphs too. 🐇
RAPTOR trees now keep their roots,
Artifacts saved in commit-shaped boots.
Redis counts each chunk in flight—
Hop hop hooray, the code compiles right!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.19% 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 is concise and accurately summarizes the main change set around knowledge compilation workflows.
Description check ✅ Passed The description includes the required Summary section and a Validation section, so it matches the repository template well enough.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

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

@KevinHuSh KevinHuSh added the ci Continue Integration label Jul 1, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft July 1, 2026 03:07
@KevinHuSh
KevinHuSh marked this pull request as ready for review July 1, 2026 03:07
@KevinHuSh KevinHuSh changed the title Add knowledge compilation workflows Feat: Add knowledge compilation workflows Jul 1, 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: 6

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/svr/task_executor.py (1)

1540-1546: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Missing artifact branch in do_handle_task — falls through to standard chunking.

skill now short-circuits explicitly, but there is no equivalent elif task_type == "artifact": branch anywhere in this function. An artifact task reaching do_handle_task (via TE_RUN_MODE="1" dry-run comparison, or the legacy else "original version" path) will fall into the final else: # Standard chunking methods branch and run build_chunks/embedding/insert_chunks against a KB-level fan-out task — logic that isn't designed for artifact tasks.

🐛 Proposed fix
     elif task_type == "skill":
         progress_callback(-1, "Skill generation requires the refactored task executor (TE_RUN_MODE=0).")
         return
+    elif task_type == "artifact":
+        progress_callback(-1, "Artifact compilation requires the refactored task executor (TE_RUN_MODE=0).")
+        return
     else:
         # Standard chunking methods
🤖 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.py` around lines 1540 - 1546, The do_handle_task flow
is missing an explicit artifact short-circuit, so artifact tasks can fall
through into the standard chunking path. Add an elif task_type == "artifact"
branch near the existing mindmap/skill handling in do_handle_task that exits
before the final standard chunking logic, and make sure the artifact path is
handled consistently in both the TE_RUN_MODE="1" comparison flow and the legacy
original-version branch. Use the existing task_type checks in do_handle_task as
the place to wire this in.
🟠 Major comments (19)
rag/svr/task_executor_refactor/raptor_service.py-742-753 (1)

742-753: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Use provenance to avoid false graph edges.

The graph projection now loads source_chunk_ids, but relations still connect every layer-K node to every layer-(K-1) node. That creates incorrect parent/child edges and can grow quadratically; connect only when provenance overlaps/subsets, with fan-out as a legacy fallback for rows without provenance.

🤖 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/raptor_service.py` around lines 742 - 753, The
layered relation builder in raptor_service.py is still creating dense
parent/child edges in the fan-out loop, which can produce false connections even
though source_chunk_ids are available. Update the relation construction logic
around the layered fan-out block to first check provenance overlap/subset
between each parent and child, only adding an edge when the child’s provenance
is supported by the parent; keep the current all-to-all fan-out behavior only as
a fallback for rows that lack provenance. Use the existing by_layer /
layers_sorted relation-building code as the place to apply this filter.
rag/svr/task_executor_refactor/raptor_service.py-69-71 (1)

69-71: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Count descriptions in tree token totals.

Tree rows store the full summary under description, but the token counter only sums title. That undercounts the generated tree payload versus the legacy per-summary accounting.

🐛 Proposed fix
         title = node.get("title")
         if isinstance(title, str) and title:
             total += num_tokens_from_string(title)
+        description = node.get("description")
+        if isinstance(description, str) and description:
+            total += num_tokens_from_string(description)
🤖 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/raptor_service.py` around lines 69 - 71, The
tree token aggregation in raptor_service.py only counts node title text and
misses the row description payload, so update the token counting logic in the
tree traversal to include description alongside title. Locate the summary-token
calculation around the node field checks in the tree-building/token-total path
and ensure both title and description are counted when present, using the same
token helper already used for title.
rag/svr/task_executor_refactor/raptor_service.py-497-507 (1)

497-507: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Persist classic summary provenance too.

This branch discards source_chunk_ids, but _persist_raptor_graph_to_es() later loads that field to build graph entities. Classic RAPTOR rows will therefore lose source deep-link provenance.

🐛 Proposed fix
-            for idx, (content, vctr, _, _) in enumerate(processed_chunks[original_length:], start=original_length):
+            for idx, (content, vctr, source_chunk_ids, _) in enumerate(processed_chunks[original_length:], start=original_length):
                 d = copy.deepcopy(doc)
                 d["id"] = make_raptor_summary_chunk_id(content, doc_id)
@@
                 d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
                 d["raptor_layer_int"] = chunk_layer.get(idx, 1)
+                if source_chunk_ids:
+                    d["source_chunk_ids"] = list(source_chunk_ids)
                 res.append(d)
🤖 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/raptor_service.py` around lines 497 - 507,
Persist the classic RAPTOR summary provenance in the chunk construction loop
inside raptor_service.py: the branch that builds `d` for summary chunks
currently drops source_chunk_ids, but `_persist_raptor_graph_to_es()` expects
that field to create graph entities. When creating each summary record in the
`processed_chunks[original_length:]` path, carry forward the original chunk
provenance from the source data into `d["source_chunk_ids"]` so classic summary
rows keep their deep-link references.
rag/svr/task_executor_refactor/raptor_utils.py-70-76 (1)

70-76: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Also delete persisted RAPTOR graph rows.

This cleanup now removes legacy/tree RAPTOR rows, but leaves the new compile_kwd="raptor_graph" row behind. The structure-graph API can still surface that stale graph after the underlying summaries are deleted.

🐛 Proposed fix
         await thread_pool_exec(
             settings.docStoreConn.delete,
             {"doc_id": doc_id, "raptor_kwd": ["raptor", "raptor_tree"]},
             nlp_search.index_name(tenant_id),
             kb_id,
         )
+        await thread_pool_exec(
+            settings.docStoreConn.delete,
+            {"doc_id": doc_id, "compile_kwd": ["raptor_graph"]},
+            nlp_search.index_name(tenant_id),
+            kb_id,
+        )
🤖 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/raptor_utils.py` around lines 70 - 76, The
cleanup in raptor_utils.py only deletes the legacy/tree RAPTOR summary rows and
still leaves the persisted graph row behind. Update the same delete path that
uses settings.docStoreConn.delete inside the cleanup block to also remove the
compile_kwd="raptor_graph" entry for the given doc_id, alongside the existing
raptor_kwd values, so reruns fully reset RAPTOR state.
rag/utils/redis_conn.py-209-215 (1)

209-215: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Separate Redis errors from NX misses in set_if_absent

credit_doc_chunking_task() treats a falsey return as “already credited”, so Redis exceptions are indistinguishable from a normal NX miss and can leave the chunking counter unreduced. Return None or raise on error, and handle that path separately from the NX miss.

🤖 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/utils/redis_conn.py` around lines 209 - 215, The set_if_absent method in
RedisDB currently returns False for both a normal NX miss and Redis exceptions,
which makes credit_doc_chunking_task() treat failures as “already credited.”
Update set_if_absent to distinguish these paths by returning None or raising on
exception instead of False, and then adjust the caller to handle the error case
separately from the NX-miss case.
api/db/services/task_service.py-61-78 (1)

61-78: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Make chunking crediting atomic
credit_doc_chunking_task() can set the done sentinel and then fail before consuming the pending counter. After that, retries short-circuit on the done key, and a missing/expired pending key can leave the counter negative; either case skips post-processing. Move both writes into one atomic Redis helper/Lua script.

🤖 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 `@api/db/services/task_service.py` around lines 61 - 78, Make
credit_doc_chunking_task() atomic: it currently writes the done sentinel with
set_if_absent() and then decrements the pending counter separately, which can
leave state inconsistent on failure or retry. Update the logic in
credit_doc_chunking_task() to use a single atomic Redis helper/Lua script that
checks the task_id done key, sets it, and decrements the doc_id pending key
together. Keep the same return semantics for first-time credits versus retries
so callers still rely on the pending count correctly.
rag/advanced_rag/knowlege_compile/structure.py-922-938 (1)

922-938: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve template metadata when rebuilding merged rows.

Merged docs are rebuilt without compilation_template_ids / compilation_template_kind_kwd, and ES dedup does not fetch those fields for old_doc. After a merge, rows can fall back to legacy grouping and future dedup can cross template boundaries.

Proposed fix
     select_fields = [
         "id", "content_with_weight", "source_chunk_ids", "knowledge_graph_kwd", "compile_kwd",
-        "doc_id", "from_entity_kwd", "to_entity_kwd",
+        "doc_id", "from_entity_kwd", "to_entity_kwd",
+        "compilation_template_ids", "compilation_template_kind_kwd",
     ]
     new_doc = _struct_to_es_doc(
         payload=payload,
         compile_kwd=base_doc.get("compile_kwd"),
         doc_id=base_doc.get("doc_id"),
         chunk_ids=chunk_ids,
         vec=vec,
         kind=kind,
         src_field=src_field,
         target_field=target_field,
+        compilation_template_id=_struct_doc_template_id(base_doc),
+        compilation_template_kind=base_doc.get("compilation_template_kind_kwd"),
     )

Also applies to: 1066-1069

🤖 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/structure.py` around lines 922 - 938,
Preserve the template metadata when rebuilding merged docs in _struct_to_es_doc
/ the merge rebuild path. The rebuilt new_doc is currently missing
compilation_template_ids and compilation_template_kind_kwd, which can cause
merged rows to lose template scoping and dedup across boundaries. Copy these
fields from base_doc into new_doc alongside the existing id and entity keyword
preservation, and make sure the same fix is applied in the related merge logic
referenced by the duplicate comment.
rag/advanced_rag/knowlege_compile/structure.py-1549-1597 (1)

1549-1597: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Wire chain validation into the merge path.

validate_and_correct_chain() is defined, but merge_compiled_structures() goes straight from local dedup to ES persistence. List/timeline branch or cycle violations therefore persist despite the added validator.

🤖 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/structure.py` around lines 1549 - 1597,
merge_compiled_structures currently skips chain validation, so invalid
list/timeline structure can still be persisted after _struct_local_dedup.
Integrate validate_and_correct_chain into the merge flow before ES writes,
applying it to each deduped structure (or its relation chain) and using the
corrected output for subsequent persistence. Make sure the validation step is
wired in alongside _struct_local_dedup and before any update/insert logic, so
cycle or branch violations are normalized or rejected consistently.
rag/advanced_rag/knowlege_compile/structure.py-86-92 (1)

86-92: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Don’t normalize distinct template kinds to timeline.

Line 91 makes page_index and knowledge_graph compile as timeline, which can route built-in templates to the wrong compile_kwd/chain behavior and collide semantically with real timeline templates.

Proposed fix
 def _struct_normalize_kind(kind) -> str:
     if not isinstance(kind, str):
         return ""
     normalized = kind.strip().lower().replace("-", "_")
-    if normalized in {"pageindex", "page_index", "knowledge_graph"}:
-        return "timeline"
-    return normalized
+    aliases = {
+        "pageindex": "page_index",
+        "knowledgegraph": "knowledge_graph",
+    }
+    return aliases.get(normalized, normalized)
🤖 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/structure.py` around lines 86 - 92, The
_struct_normalize_kind helper is collapsing distinct template kinds into
"timeline", which can send built-in templates through the wrong compile_kwd path
and chain behavior. Update _struct_normalize_kind so it only normalizes
formatting (case, hyphens/underscores) and preserves semantic kind names like
page_index and knowledge_graph instead of remapping them; keep the existing
behavior in structure.py aligned with the compile/dispatch logic that uses the
normalized kind.
api/apps/services/dataset_api_service.py-1835-1836 (1)

1835-1836: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Use write authorization for artifact edits and wipes.

KnowledgebaseService.accessible includes team-shared KB access, so a read-shared team member can edit artifact pages or clear all artifact rows. Match the stricter write/update ownership check used by document updates, or introduce a dedicated write-permission check.

Proposed fix
-    if not KnowledgebaseService.accessible(dataset_id, tenant_id):
+    if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
         return False, "No authorization."

Apply to both update_artifact_page and clear_artifacts unless team write-collaboration is explicitly intended.

Also applies to: 2395-2396

🤖 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 `@api/apps/services/dataset_api_service.py` around lines 1835 - 1836, The
authorization check for artifact mutations is too permissive because
`KnowledgebaseService.accessible` allows team-shared read access, which can let
non-owners edit artifact pages or wipe artifact rows. Update
`update_artifact_page` and `clear_artifacts` to use the same stricter
write/ownership authorization pattern as document updates, or add a dedicated
write-permission helper and call it from both methods. Keep the existing “No
authorization.” failure path, but ensure it only passes for users with write
access.
rag/advanced_rag/knowlege_compile/dataset_nav.py-287-294 (1)

287-294: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Don’t proceed lock-free after the Redis lock fails.

These paths perform read-modify-write updates; continuing without the lock can drop another executor’s nav entry. Prefer skipping the best-effort nav update when the lock cannot be acquired.

Proposed fix
     try:
         await lock.spin_acquire()
     except Exception:
         logging.exception(
-            "dataset_nav: lock acquire failed for kb=%s; proceeding lock-free",
+            "dataset_nav: lock acquire failed for kb=%s; skipping nav update",
             kb_id,
         )
+        return

Apply the same pattern in remove_dataset_nav_doc.

Also applies to: 352-358

🤖 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/dataset_nav.py` around lines 287 - 294, The
lock acquisition fallback in dataset_nav update paths is too permissive: when
`lock.spin_acquire()` fails in the nav write flow, do not continue with the
read-modify-write operation lock-free. Update the affected logic in the dataset
nav update helper(s) such as the code around the lock-acquire block and
`remove_dataset_nav_doc` so the best-effort nav update is skipped entirely after
a Redis lock failure, while keeping the existing exception logging for
observability.
api/apps/services/dataset_api_service.py-36-59 (1)

36-59: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Add the missing artifact wipe branch.

artifact is now a valid index_type, but delete_index(..., index_type="artifact", wipe=True) only resets task metadata and leaves compiled artifact rows behind.

Proposed fix
     elif wipe and index_type == "raptor":
         from rag.nlp import search
 
         settings.docStoreConn.delete({"raptor_kwd": ["raptor"]}, search.index_name(kb.tenant_id), dataset_id)
+    elif wipe and index_type == "artifact":
+        from rag.nlp import search
+
+        settings.docStoreConn.delete(
+            {"compile_kwd": list(_ARTIFACT_COMPILE_KWDS)},
+            search.index_name(kb.tenant_id),
+            dataset_id,
+        )
     elif wipe and index_type == "skill":
         from rag.nlp import search

Also applies to: 862-865

🤖 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 `@api/apps/services/dataset_api_service.py` around lines 36 - 59, The
delete_index flow is missing a wipe path for the new artifact index type, so
calling delete_index with index_type="artifact" and wipe=True only clears task
metadata and leaves compiled artifact rows behind. Update the delete_index
handling in dataset_api_service.py to add an artifact-specific wipe branch
alongside the existing graph/raptor/mindmap logic, using the existing constants
like _VALID_INDEX_TYPES, _INDEX_TYPE_TO_TASK_ID_FIELD, and
_INDEX_TYPE_TO_DISPLAY_NAME to keep the dispatch consistent. Make sure the
artifact branch removes the underlying artifact rows as part of wipe=True while
preserving the current metadata reset behavior.
api/apps/services/dataset_api_service.py-1743-1750 (1)

1743-1750: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard skill-tree JSON parsing.

A malformed or missing skill_with_weight field currently raises outside the doc-store try block and turns the endpoint into a 500.

Proposed fix
     _, row = next(iter(field_map.items()))
+    try:
+        skill_with_weight = json.loads(row.get("skill_with_weight") or "[]")
+    except (json.JSONDecodeError, TypeError):
+        logging.exception("get_skill_tree: invalid skill JSON for kb=%s", dataset_id)
+        skill_with_weight = []
+    if not isinstance(skill_with_weight, list):
+        skill_with_weight = []
     return True, {
         "id": row.get("id"),
         "kb_id": row.get("kb_id") or dataset_id,
         "doc_id": row.get("doc_id") or dataset_id,
         "compile_kwd": row.get("compile_kwd") or _SKILL_ALL_COMPILE_KWD,
-        "skill_with_weight": json.loads(row.get("skill_with_weight")) or [],
+        "skill_with_weight": skill_with_weight,
     }
🤖 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 `@api/apps/services/dataset_api_service.py` around lines 1743 - 1750, The
skill-tree parsing in the dataset API response mapping can raise when
`skill_with_weight` is missing or malformed, causing the endpoint to fail with a
500. Update the logic in `dataset_api_service.py` around the
`field_map`/`row.get("skill_with_weight")` handling to guard the JSON parse and
return a safe default like an empty list when the field is absent or invalid.
Keep the fix localized to the response construction path that builds the result
dict so the surrounding doc-store error handling remains effective.
api/apps/services/dataset_api_service.py-2315-2318 (1)

2315-2318: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Restore the cumulative weight cap.

The overview loader documents cumulative weight budgeting, but the budget check is commented out, so the response is capped only by entity count.

Proposed fix
-            `#if` cumulative_weight + w > cap and len(entities) + len(e_sub) > 0:
-            #    break
+            if cumulative_weight + w > cap:
+                break
             cumulative_weight += w
🤖 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 `@api/apps/services/dataset_api_service.py` around lines 2315 - 2318, The
cumulative weight budget check in the overview loader is currently disabled, so
the cap is enforced only by entity count. Re-enable the guard in the entity
accumulation logic inside the overview-loading path of dataset_api_service.py
(near the code that updates cumulative_weight and appends to e_sub), and make
sure the loop breaks once adding the next payload would exceed the configured
cap while still allowing at least one entity to be included.
api/db/services/compilation_template_group_service.py-270-271 (1)

270-271: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Persist template order explicitly.

index is computed on create/update, but _insert_child() drops it, and every read path falls back to CompilationTemplate.create_time.asc(). That makes the caller-defined template order nondeterministic whenever inserts share the same timestamp or the group is rewritten. Store an explicit sort column and read by that instead.

Also applies to: 315-316, 342-371

🤖 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 `@api/db/services/compilation_template_group_service.py` around lines 270 -
271, The template group flow is not persisting caller-defined ordering because
_insert_child() receives index but discards it, and the read paths in
CompilationTemplateGroupService still sort by
CompilationTemplate.create_time.asc(). Update the child persistence logic to
store an explicit order/sort field when inserting or updating children, and
change all group read/query paths to order by that stored field instead of
creation time so the template order remains deterministic.
api/db/services/compilation_template_service.py-125-128 (1)

125-128: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Fix the Peewee boolean filters and add a seeding log

  • Replace the == True/False checks at api/db/services/compilation_template_service.py:127, 146, 157, 168 with cls.model.is_builtin / not cls.model.is_builtin so ruff check passes.
  • Add a success log in seed_builtins_from_files() for the new startup flow.
🤖 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 `@api/db/services/compilation_template_service.py` around lines 125 - 128,
Update the Peewee boolean filters in CompilationTemplateService to use direct
truthiness checks instead of explicit comparisons: replace the `== False` and
any matching `== True` usages in the query helpers with `not
cls.model.is_builtin` or `cls.model.is_builtin` so `ruff check` is satisfied.
Also add a success log inside `seed_builtins_from_files()` after the built-in
templates are seeded, using the existing service logger pattern to confirm the
startup seeding flow completed.

Sources: Coding guidelines, Linters/SAST tools

api/db/init_data/compilation_templates/empty.yaml-5-17 (1)

5-17: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Make the empty builtin actually pass template validation.

This seed defines blank placeholder entries in entity.fields and relation.fields, but validate_template_payload() rejects every listed field unless type and description are non-empty. As shipped, the “Empty” builtin cannot be saved unchanged from the group API.

Suggested fix
 config:
   kind: empty
   entity:
     description: ''
-    fields:
-      - type: ''
-        description: ''
-        rule: ''
+    fields: []
   relation:
     description: ''
-    fields:
-      - type: ''
-        description: ''
-        rule: ''
+    fields: []
   global_rules: ''
🤖 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 `@api/db/init_data/compilation_templates/empty.yaml` around lines 5 - 17, The
Empty builtin template still fails validation because the placeholder entries in
entity.fields and relation.fields use blank type/description values that
validate_template_payload() rejects. Update the empty.yaml template so the
builtin can pass unchanged, either by removing those placeholder field entries
entirely or by giving them valid non-empty defaults that satisfy the template
schema, keeping the entity, relation, and global_rules structure intact.
api/apps/restful_apis/utils/compilation_template_validation.py-43-77 (1)

43-77: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard nested template sections before calling .get().

A payload like {"config": {"entity": "oops"}} or {"config": {"claim": {"fields": {"x": 1}}}} will raise AttributeError here instead of returning a validation message. These values are user-controlled, so the helper needs to reject non-dict sections / non-list fields explicitly.

Suggested fix
         for section in ["entity", "relation"]:
-            fields = ((config.get(section) or {}).get("fields") or [])
+            section_config = config.get(section) or {}
+            if not isinstance(section_config, dict):
+                return f"Invalid {section} section."
+            fields = section_config.get("fields") or []
+            if not isinstance(fields, list):
+                return f"Invalid {section} fields."
             seen_types = set()
             for field in fields:
+                if not isinstance(field, dict):
+                    return f"Invalid {section} field."
                 field_type = str((field or {}).get("type") or "").strip()
                 if not field_type:
                     return f"{section.capitalize()} type is required."
@@
         if config.get("kind") == "artifacts" or req.get("kind") == "artifacts":
-            for field in ((config.get("claim") or {}).get("fields") or []):
+            claim_config = config.get("claim") or {}
+            concept_config = config.get("concept") or {}
+            if not isinstance(claim_config, dict) or not isinstance(concept_config, dict):
+                return "Invalid artifacts template section."
+            claim_fields = claim_config.get("fields") or []
+            concept_fields = concept_config.get("fields") or []
+            if not isinstance(claim_fields, list) or not isinstance(concept_fields, list):
+                return "Invalid artifacts template fields."
+            for field in claim_fields:
+                if not isinstance(field, dict):
+                    return "Invalid claim field."
                 if not str((field or {}).get("statement") or "").strip():
                     return "Claim statement is required."
@@
-            for field in ((config.get("concept") or {}).get("fields") or []):
+            for field in concept_fields:
+                if not isinstance(field, dict):
+                    return "Invalid concept field."
                 if not str((field or {}).get("term") or "").strip():
                     return "Concept term is required."
🤖 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 `@api/apps/restful_apis/utils/compilation_template_validation.py` around lines
43 - 77, The validation helper in compilation_template_validation.py should
defensively reject malformed nested sections before using .get() on them. Update
the validation logic that iterates through the entity/relation/claim/concept
blocks so it first verifies each section is a dict and each fields value is a
list, then return a validation error instead of allowing AttributeError for
inputs like a string entity or a dict fields value. Keep the existing checks in
the same helper and apply the same guard pattern wherever nested config sections
are accessed.
api/apps/restful_apis/compilation_template_group_api.py-72-77 (1)

72-77: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Validate pagination params before calling int().

page and page_size are parsed before the handler’s try, so a request like ?page=abc raises ValueError and turns into a 500 instead of a data error.

Suggested fix
 def list_groups() -> Response:
-    keywords = request.args.get("keywords", "")
-    scope = request.args.get("scope", "")
-    page_number = int(request.args.get("page", 0))
-    items_per_page = validate_rest_api_page_size(int(request.args.get("page_size", 0)))
-    orderby = request.args.get("orderby", "create_time")
-    desc = request.args.get("desc", "true").lower() != "false"
-
     try:
+        keywords = request.args.get("keywords", "")
+        scope = request.args.get("scope", "")
+        page_number = int(request.args.get("page", 0))
+        items_per_page = validate_rest_api_page_size(int(request.args.get("page_size", 0)))
+        orderby = request.args.get("orderby", "create_time")
+        desc = request.args.get("desc", "true").lower() != "false"
+    except ValueError:
+        return get_data_error_result(message="Invalid pagination parameters.")
+
+    try:
         groups = CompilationTemplateGroupService.list_saved(
             current_user.id, keywords, scope, orderby, desc
         )
🤖 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 `@api/apps/restful_apis/compilation_template_group_api.py` around lines 72 -
77, The pagination parsing in the handler is doing int() conversion for page and
page_size before the existing try/validation path, so invalid query values can
raise ValueError and escape as a 500. Move the parsing of
request.args.get("page") and request.args.get("page_size") into the same
validated flow used by CompilationTemplateGroupAPI, and keep
validate_rest_api_page_size as the guard so bad inputs are handled as
request/data errors instead of uncaught exceptions.
🟡 Minor comments (3)
rag/raptor.py-319-326 (1)

319-326: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass random_state into UMAP. This call currently ignores the RAPTOR seed; umap-learn supports random_state, so wiring it through keeps the clustering/tree shape reproducible across runs.

🤖 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/raptor.py` around lines 319 - 326, The UMAP reduction in raptor.py does
not use the RAPTOR seed, so the tree/clustering can vary between runs. Update
the UMAP(...) call in the embedding reduction block to pass the existing RAPTOR
seed through as random_state, using the nearby embedding reduction logic where
reduced_embeddings is created, so the output stays reproducible across runs.
rag/advanced_rag/knowlege_compile/_common.py-878-896 (1)

878-896: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Sort __all__ to satisfy Ruff.

RUF022 flags this list; sorting it keeps the new file compatible with ruff check.

As per coding guidelines, **/*.py: Use ruff for Python linting and formatting with commands ruff check and ruff format.

🤖 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/_common.py` around lines 878 - 896, The
__all__ list in _common.py is not sorted, which triggers Ruff RUF022. Reorder
the exports in __all__ alphabetically while keeping all existing symbols like
stable_row_id, ensure_llm_bundle, normalize_key, and DEFAULT_DISAMBIGUATE_SYSTEM
included so the module passes ruff check.

Sources: Coding guidelines, Linters/SAST tools

rag/advanced_rag/knowlege_compile/__init__.py-31-43 (1)

31-43: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Sort __all__ to satisfy Ruff.

RUF022 flags this export list, so ruff check can fail on this new module.

Proposed fix
 __all__ = [
-    "compile_structure_from_text",
-    "merge_compiled_structures",
-    "artifact_map_from_chunks",
-    "artifact_reduce_from_extracts",
-    "artifact_plan_from_reduction",
-    "artifact_refine_from_plan",
+    "ARTIFACT_DRAFT_COMPILE_KWD",
     "ARTIFACT_MAP_COMPILE_KWD",
-    "ARTIFACT_REDUCE_COMPILE_KWD",
-    "ARTIFACT_PLAN_COMPILE_KWD",
     "ARTIFACT_PAGE_COMPILE_KWD",
-    "ARTIFACT_DRAFT_COMPILE_KWD",
+    "ARTIFACT_PLAN_COMPILE_KWD",
+    "ARTIFACT_REDUCE_COMPILE_KWD",
+    "artifact_map_from_chunks",
+    "artifact_plan_from_reduction",
+    "artifact_reduce_from_extracts",
+    "artifact_refine_from_plan",
+    "compile_structure_from_text",
+    "merge_compiled_structures",
 ]

As per coding guidelines, **/*.py: Use ruff for Python linting and formatting with commands ruff check and ruff format.

🤖 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/__init__.py` around lines 31 - 43, Sort the
module export list in __all__ to satisfy Ruff’s RUF022 rule and keep ruff check
passing. Update the __all__ declaration in the knowledge_compile package so the
exported names are ordered consistently (for example, alphabetically) while
preserving the same symbols like compile_structure_from_text,
merge_compiled_structures, and the ARTIFACT_* constants.

Sources: Coding guidelines, Linters/SAST tools

🧹 Nitpick comments (8)
api/db/services/pipeline_operation_log_service.py (1)

153-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider collapsing the per-task-type finish_at branches into a lookup table.

Five near-identical if/elif blocks now just map task_type → a KB column name. A dict keeps this DRY and makes adding the next fan-out task type a one-line change.

♻️ Proposed refactor
+            _FINISH_AT_FIELD_BY_TASK_TYPE = {
+                PipelineTaskType.GRAPH_RAG: "graphrag_task_finish_at",
+                PipelineTaskType.RAPTOR: "raptor_task_finish_at",
+                PipelineTaskType.MINDMAP: "mindmap_task_finish_at",
+                PipelineTaskType.ARTIFACT: "artifact_task_finish_at",
+                PipelineTaskType.SKILL: "skill_task_finish_at",
+            }
             finish_at = process_begin_at + timedelta(seconds=process_duration)
-            if task_type == PipelineTaskType.GRAPH_RAG:
-                KnowledgebaseService.update_by_id(
-                    document.kb_id,
-                    {"graphrag_task_finish_at": finish_at},
-                )
-            elif task_type == PipelineTaskType.RAPTOR:
-                KnowledgebaseService.update_by_id(
-                    document.kb_id,
-                    {"raptor_task_finish_at": finish_at},
-                )
-            elif task_type == PipelineTaskType.MINDMAP:
-                KnowledgebaseService.update_by_id(
-                    document.kb_id,
-                    {"mindmap_task_finish_at": finish_at},
-                )
-            elif task_type == PipelineTaskType.ARTIFACT:
-                KnowledgebaseService.update_by_id(
-                    document.kb_id,
-                    {"artifact_task_finish_at": finish_at},
-                )
-            elif task_type == PipelineTaskType.SKILL:
-                KnowledgebaseService.update_by_id(
-                    document.kb_id,
-                    {"skill_task_finish_at": finish_at},
-                )
+            field = _FINISH_AT_FIELD_BY_TASK_TYPE.get(task_type)
+            if field:
+                KnowledgebaseService.update_by_id(document.kb_id, {field: finish_at})
🤖 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 `@api/db/services/pipeline_operation_log_service.py` around lines 153 - 178,
Collapse the repeated task-type branches in PipelineOperationLogService by
replacing the if/elif chain with a lookup table that maps each PipelineTaskType
value to the corresponding KnowledgebaseService field name. Keep the existing
finish_at calculation and then resolve the update payload from that mapping
before calling KnowledgebaseService.update_by_id, so adding new task types only
requires extending the map.
rag/svr/task_executor.py (1)

1544-1546: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging alongside the new skill early-return.

The early return only calls progress_callback; no logging.* call records this path was hit, making it harder to diagnose in server logs why a skill task didn't run.

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

♻️ Proposed addition
     elif task_type == "skill":
+        logging.warning(f"Task {task['id']}: skill task type not supported in legacy task executor (TE_RUN_MODE={os.environ.get('TE_RUN_MODE', '0')}).")
         progress_callback(-1, "Skill generation requires the refactored task executor (TE_RUN_MODE=0).")
         return
🤖 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.py` around lines 1544 - 1546, The new skill
early-return in task_executor.py only reports through progress_callback, so add
a logging call in the same skill branch before returning to record that this
path was taken. Update the task executor’s skill-handling flow around the `elif
task_type == "skill"` block so server logs clearly show why the task did not
proceed, while keeping the existing progress_callback message intact.

Source: Coding guidelines

api/db/services/task_service.py (1)

511-525: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add lifecycle logging for the new counter flow.

Log when the pending counter is initialized and when it is cleared after queueing failure; this is the only breadcrumb for diagnosing stuck chunking finalizers. As per coding guidelines, "**/*.py: Add logging for new flows".

Suggested logging
     if chunking_n > 0:
         assert REDIS_CONN.set(
             _doc_chunking_pending_key(doc["id"]),
             str(chunking_n),
             exp=DOC_CHUNKING_COUNTER_TTL_SECONDS,
         ), "Can't access Redis. Please check the Redis' status."
+        logging.info("Initialized chunking pending counter for doc %s: %s", doc["id"], chunking_n)
@@
     except Exception:
+        logging.exception("Failed to queue chunking tasks for doc %s; clearing pending counter", doc["id"])
         clear_doc_chunking_counter(doc["id"])
         raise
🤖 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 `@api/db/services/task_service.py` around lines 511 - 525, Add lifecycle
logging around the new pending counter flow in task_service’s chunking finalizer
path. In the block that initializes the doc chunking pending counter and in the
exception handler that calls clear_doc_chunking_counter, emit logs that clearly
state when the counter is set and when it is cleared after a queueing failure.
Use the existing task_service logic around _doc_chunking_pending_key,
clear_doc_chunking_counter, and REDIS_CONN.queue_product so the breadcrumb is
tied to this flow.

Source: Coding guidelines

api/db/services/compilation_template_service.py (1)

195-234: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log builtin template seeding.

This is a new startup flow, but successful runs are silent. A small info log with the template directory and loaded/upserted count would make initialization failures much easier to diagnose. As per coding guidelines, "Add logging for new flows."

🤖 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 `@api/db/services/compilation_template_service.py` around lines 195 - 234, The
builtin template seeding flow in seed_builtins_from_files and
load_builtins_from_files is silent on success, so add an info-level startup log
for this new path. Log the template directory being scanned and the number of
templates loaded and upserted, using the existing seed_builtins_from_files and
load_builtins_from_files symbols so the initialization flow is easy to trace.
Keep the existing warning/exception handling, but make the successful seeding
path visible in logs.

Source: Coding guidelines

api/db/services/compilation_template_group_service.py (1)

255-339: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logs around group mutations.

Create/update/delete are new write flows, but they are silent unless an exception escapes. An info log with the action, tenant_id, and group_id would make support/debugging much easier. As per coding guidelines, "Add logging for new flows."

🤖 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 `@api/db/services/compilation_template_group_service.py` around lines 255 -
339, Add info logging for the new write flows in CompilationTemplateGroupService
so create_group, update_group, and delete_group are observable during
support/debugging. Log the action plus tenant_id and group_id (use the generated
id in create_group, the passed group_id in update_group/delete_group) around the
successful mutation path, keeping the logging close to these methods and their
DB.atomic() blocks.

Source: Coding guidelines

api/apps/restful_apis/document_api.py (1)

272-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log when template-group changes force a reparse.

This branch can now clear chunks and reset progress solely because compilation_template_group_id changed. Please add a structured log before reset_document_for_reparse() so operators can tell why an otherwise unchanged document was reparsed.

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

Source: Coding guidelines

api/apps/restful_apis/compilation_template_api.py (1)

29-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logs around the builtin seed/fallback path.

This endpoint now has a non-trivial flow: read DB → seed builtins on demand → fall back to file-loaded templates. A couple of info/warning logs here would make it much easier to explain why a GET request ended up mutating or bypassing persisted builtin state.

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

🤖 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 `@api/apps/restful_apis/compilation_template_api.py` around lines 29 - 55, Add
logging in list_builtin_templates to make the builtin read/seed/fallback flow
observable: emit an info or warning when
CompilationTemplateService.list_builtins() returns empty and
seed_builtins_from_files() is triggered, and another log when the code falls
back to CompilationTemplateService.load_builtins_from_files(). Keep the logs
close to the existing try block in list_builtin_templates and include enough
context to tell whether the response came from the DB, the seed path, or the
file-loaded fallback.

Source: Coding guidelines

api/apps/restful_apis/compilation_template_group_api.py (1)

69-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add structured logs for the new group CRUD flows.

These endpoints introduce new list/detail/create/update/delete paths, but nothing records request outcomes or the branches that reject duplicates / missing groups. A few structured logs would materially improve operability here.

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

Also applies to: 91-100, 103-127, 130-174

🤖 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 `@api/apps/restful_apis/compilation_template_group_api.py` around lines 69 -
88, The new compilation template group CRUD handlers currently return
success/error responses without any structured logging, so add logs in the
relevant route functions to capture request outcomes and rejection branches.
Update list_groups and the other affected endpoints in this module (the
create/update/delete/detail handlers) to log key events via the existing logger
patterns, especially when a group is missing or a duplicate is rejected, and
include identifying context such as current_user.id, group identifiers, and the
action name so the new flows are observable.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b61bed1c-e275-4015-b540-e8a2b70a261e

📥 Commits

Reviewing files that changed from the base of the PR and between 828c578 and a50ee2d.

📒 Files selected for processing (44)
  • api/apps/restful_apis/chunk_api.py
  • api/apps/restful_apis/compilation_template_api.py
  • api/apps/restful_apis/compilation_template_group_api.py
  • api/apps/restful_apis/dataset_api.py
  • api/apps/restful_apis/document_api.py
  • api/apps/restful_apis/utils/compilation_template_validation.py
  • api/apps/services/dataset_api_service.py
  • api/apps/services/document_api_service.py
  • api/db/__init__.py
  • api/db/db_models.py
  • api/db/init_data.py
  • api/db/init_data/compilation_templates/artifacts.yaml
  • api/db/init_data/compilation_templates/empty.yaml
  • api/db/init_data/compilation_templates/knowledge_graph.yaml
  • api/db/init_data/compilation_templates/mind_map.yaml
  • api/db/init_data/compilation_templates/page_index.yaml
  • api/db/init_data/compilation_templates/timeline.yaml
  • api/db/init_data/compilation_templates/tree.yaml
  • api/db/services/artifact_commit_service.py
  • api/db/services/compilation_template_group_service.py
  • api/db/services/compilation_template_service.py
  • api/db/services/dialog_service.py
  • api/db/services/document_service.py
  • api/db/services/knowledgebase_service.py
  • api/db/services/pipeline_operation_log_service.py
  • api/db/services/task_service.py
  • api/utils/validation_utils.py
  • common/constants.py
  • rag/advanced_rag/knowlege_compile/__init__.py
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/artifact.py
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/flow/extractor/extractor.py
  • rag/graphrag/general/mind_map_extractor.py
  • rag/nlp/search.py
  • rag/prompts/generator.py
  • rag/raptor.py
  • rag/svr/task_executor.py
  • rag/svr/task_executor_refactor/raptor_service.py
  • rag/svr/task_executor_refactor/raptor_utils.py
  • rag/svr/task_executor_refactor/task_handler.py
  • rag/utils/es_conn.py
  • rag/utils/redis_conn.py
💤 Files with no reviewable changes (1)
  • rag/graphrag/general/mind_map_extractor.py

Comment on lines +689 to +694
for row in (rows or {}).values():
graph = {}
try:
graph = json.loads(row.get("content_with_weight") or "{}")
except Exception:
continue

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.

📐 Maintainability & Code Quality | 🔴 Critical | ⚡ Quick win

Log malformed structure graph rows instead of silently skipping them.

Ruff flags this try/except/continue pattern, and silent skips make corrupted graph rows hard to diagnose.

Proposed fix
-    for row in (rows or {}).values():
+    for row_id, row in (rows or {}).items():
         graph = {}
         try:
             graph = json.loads(row.get("content_with_weight") or "{}")
-        except Exception:
+        except (json.JSONDecodeError, TypeError):
+            logging.warning(
+                "structure_graph: invalid graph JSON row=%s doc=%s",
+                row_id,
+                document_id,
+            )
             continue

As per coding guidelines, use ruff for Python linting and add logging for new flows.

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

Suggested change
for row in (rows or {}).values():
graph = {}
try:
graph = json.loads(row.get("content_with_weight") or "{}")
except Exception:
continue
for row_id, row in (rows or {}).items():
graph = {}
try:
graph = json.loads(row.get("content_with_weight") or "{}")
except (json.JSONDecodeError, TypeError):
logging.warning(
"structure_graph: invalid graph JSON row=%s doc=%s",
row_id,
document_id,
)
continue
🧰 Tools
🪛 Ruff (0.15.20)

[error] 693-694: try-except-continue detected, consider logging the exception

(S112)


[warning] 693-693: Do not catch blind exception: Exception

(BLE001)

🤖 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 `@api/apps/restful_apis/chunk_api.py` around lines 689 - 694, The loop in the
graph-row parsing block currently swallows malformed `content_with_weight`
values by catching Exception and continuing silently. Update this logic in the
row-processing code to log a warning/error with enough context from the row
before skipping, and keep the existing fallback behavior after logging. Use the
existing graph parsing flow around the json.loads call so corrupted rows are
still ignored, but are now diagnosable and compliant with Ruff and logging
guidelines.

Sources: Coding guidelines, Linters/SAST tools

Comment thread api/apps/restful_apis/dataset_api.py Resolved
Comment on lines +2019 to +2024
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
payload = parsed
except Exception:
pass

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.

📐 Maintainability & Code Quality | 🔴 Critical | ⚡ Quick win

Log JSON parse failures in artifact graph payload helpers.

Ruff flags these except: pass blocks, and malformed compiled rows should be observable.

Proposed fix
-        except Exception:
-            pass
+        except (json.JSONDecodeError, TypeError):
+            logging.debug("invalid artifact entity payload JSON", exc_info=True)
-        except Exception:
-            pass
+        except (json.JSONDecodeError, TypeError):
+            logging.debug("invalid artifact relation payload JSON", exc_info=True)

As per coding guidelines, add logging for new flows and use ruff for Python linting.

Also applies to: 2046-2051

🧰 Tools
🪛 Ruff (0.15.20)

[error] 2023-2024: try-except-pass detected, consider logging the exception

(S110)


[warning] 2023-2023: Do not catch blind exception: Exception

(BLE001)

🤖 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 `@api/apps/services/dataset_api_service.py` around lines 2019 - 2024, The
artifact graph payload helper currently swallows JSON parsing errors with a bare
exception handler, so malformed rows are invisible. Update the parsing logic in
the helper around the json.loads call to log the failure before falling back,
using the existing logger in dataset_api_service and keeping the payload
handling behavior unchanged. Apply the same fix in the other matching helper
referenced by the review so both compiled-row parsing paths report invalid JSON
instead of passing silently.

Sources: Coding guidelines, Linters/SAST tools

Comment thread rag/flow/extractor/extractor.py Resolved
Comment on lines +767 to 794
def _normalize(item):
if len(item) >= 3:
text, vec, src = item[0], item[1], item[2]
else:
text, vec = item[0], item[1]
src = []
if not text or vec is None or len(vec) <= 0:
return None
# Defensive: a leaf should carry a list of strings. Drop
# falsy entries so we don't propagate empty ids upward.
if isinstance(src, (list, tuple)):
src = [s for s in src if s]
else:
src = [src] if src else []
return (text, vec, list(src), "")

normalized = [t for t in (_normalize(c) for c in chunks) if t is not None]
if len(normalized) <= 1:
return None if is_tree else (normalized, [(0, len(normalized))])
chunks = normalized

if self._tree_builder == PSI_TREE_BUILDER:
if is_tree:
raise NotImplementedError(
"is_tree=True is not supported for PSI_TREE_BUILDER",
)
logging.info("RAPTOR: using %s tree builder for %d chunks", self._tree_builder, len(chunks))
return await self._build_psi_layers(chunks, callback, task_id)

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Keep normalized originals as 3-tuples before PSI dispatch.

_normalize() returns a 4-tuple, but the PSI path sends those entries into _build_psi_structure(), which unpacks (text, embd, src). Selecting PSI_TREE_BUILDER will crash before summarization.

🐛 Proposed fix
-            return (text, vec, list(src), "")
+            return (text, vec, list(src))
📝 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.

Suggested change
def _normalize(item):
if len(item) >= 3:
text, vec, src = item[0], item[1], item[2]
else:
text, vec = item[0], item[1]
src = []
if not text or vec is None or len(vec) <= 0:
return None
# Defensive: a leaf should carry a list of strings. Drop
# falsy entries so we don't propagate empty ids upward.
if isinstance(src, (list, tuple)):
src = [s for s in src if s]
else:
src = [src] if src else []
return (text, vec, list(src), "")
normalized = [t for t in (_normalize(c) for c in chunks) if t is not None]
if len(normalized) <= 1:
return None if is_tree else (normalized, [(0, len(normalized))])
chunks = normalized
if self._tree_builder == PSI_TREE_BUILDER:
if is_tree:
raise NotImplementedError(
"is_tree=True is not supported for PSI_TREE_BUILDER",
)
logging.info("RAPTOR: using %s tree builder for %d chunks", self._tree_builder, len(chunks))
return await self._build_psi_layers(chunks, callback, task_id)
def _normalize(item):
if len(item) >= 3:
text, vec, src = item[0], item[1], item[2]
else:
text, vec = item[0], item[1]
src = []
if not text or vec is None or len(vec) <= 0:
return None
# Defensive: a leaf should carry a list of strings. Drop
# falsy entries so we don't propagate empty ids upward.
if isinstance(src, (list, tuple)):
src = [s for s in src if s]
else:
src = [src] if src else []
return (text, vec, list(src))
normalized = [t for t in (_normalize(c) for c in chunks) if t is not None]
if len(normalized) <= 1:
return None if is_tree else (normalized, [(0, len(normalized))])
chunks = normalized
if self._tree_builder == PSI_TREE_BUILDER:
if is_tree:
raise NotImplementedError(
"is_tree=True is not supported for PSI_TREE_BUILDER",
)
logging.info("RAPTOR: using %s tree builder for %d chunks", self._tree_builder, len(chunks))
return await self._build_psi_layers(chunks, callback, task_id)
🤖 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/raptor.py` around lines 767 - 794, The PSI path in raptor.py is passing
normalized items in the wrong shape, causing _build_psi_structure() to fail when
it expects (text, embd, src). Update _normalize() and the PSI dispatch in the
chunk-building flow so the PSI_TREE_BUILDER branch preserves originals as
3-tuples, while any extra metadata stays separate or is stripped before calling
_build_psi_layers(). Verify the tuple shape used by
_build_psi_layers()/_build_psi_structure() matches the PSI unpacking contract
and does not include the added fourth element.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rag/advanced_rag/knowlege_compile/wiki.py (2)

88-93: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Separate the concatenated prompt literals.

These adjacent string literals collapse into [].Keep... / JSON.Keep... / wikilinks). 5. in the final prompts, which hurts prompt clarity and model parsing. Add an explicit space or newline between the sentences.

Also applies to: 1533-1544, 2406-2421

🤖 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/wiki.py` around lines 88 - 93, The prompt
strings in WIKI_MAP_SYSTEM and the other affected prompt blocks use adjacent
literals that concatenate without whitespace, so separate the sentences with an
explicit space or newline in each multi-line prompt definition. Update the
prompt assembly in the identified constants/helpers so the final text remains
readable and the model receives clean sentence boundaries, especially around the
schema/JSON instructions and the language-preservation note.

1695-1797: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Key reconciliation by kind as well as name.

entities and concepts can share the same display string, but this dict is keyed only by the bare name/term. The later item overwrites the earlier one, so one page never reaches MAYBE/UPDATE handling. Use a (kind, name) key or a nested map before _wiki_resolve_maybe_items / _wiki_planning_call consume it.

🤖 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/wiki.py` around lines 1695 - 1797, The
reconciliation map is keyed only by the bare item name, so a concept and entity
with the same display string can overwrite each other and skip MAYBE/UPDATE
handling. Update the reconciliation logic in the function that builds this map
so each entry is keyed by both kind and name (or use a nested structure), and
make sure the downstream consumers that read this map, including
_wiki_resolve_maybe_items and _wiki_planning_call, are updated to use the same
composite key shape.
🧹 Nitpick comments (3)
api/apps/restful_apis/dataset_api.py (2)

562-830: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Repeated try/success/except boilerplate across 10 handlers.

Each of the new endpoints repeats the same try: success, result = await service_call(...); if success: ...; return get_result(...); except Exception: logging.exception(...); return get_error_data_result(...) skeleton. Consider extracting a small decorator/helper (e.g. @wiki_endpoint or a _handle_service_call wrapper) to remove this duplication.

🤖 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 `@api/apps/restful_apis/dataset_api.py` around lines 562 - 830, The new
artifact/skill handlers repeat the same try/success/except response handling
pattern, so extract the shared flow into a reusable helper or decorator. Use the
existing endpoint functions like has_any_wiki, list_wiki_pages, get_wiki_graph,
clear_wiki, get_wiki_page, has_any_skill, get_skill_tree, get_skill_page,
list_wiki_commits, get_wiki_commit, and update_wiki_page as callers of a common
wrapper that logs exceptions and maps service results to
get_result/get_error_data_result.

589-593: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

No lower-bound validation on page/page_size.

int(request.args.get("page", 1) or 1) accepts "0" or negative values (e.g. page=-1) without rejection, since a non-empty string like "0" is truthy. This could pass page=0 or negative values downstream to the service/pagination logic.

Also applies to: 757-760

🤖 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 `@api/apps/restful_apis/dataset_api.py` around lines 589 - 593, The pagination
parsing in dataset_api’s request handling accepts 0 and negative values for page
and page_size because it only casts with int after request.args.get; update the
validation in the affected pagination blocks (including the shared logic used in
the other matching location) to reject values less than 1 and return
get_error_argument_result when page or page_size is not a positive integer. Use
the existing page/page_size parsing in the dataset API methods as the place to
enforce the lower bound before passing values into downstream pagination/service
calls.
rag/svr/task_executor.py (1)

1544-1546: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider logging the skill-block event, not just via progress_callback.

This is a new error-blocking flow but doesn't emit anything through the logging module, only progress_callback. If progress_callback output isn't captured in application logs/observability tooling, this failure mode becomes hard to trace.

As per coding guidelines, "Add logging for new flows" applies to **/*.py.

♻️ Suggested addition
     elif task_type == "skill":
+        logging.warning("Rejected skill task %s: requires the refactored task executor (TE_RUN_MODE=0).", task_id)
         progress_callback(-1, "Skill generation requires the refactored task executor (TE_RUN_MODE=0).")
         return
🤖 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.py` around lines 1544 - 1546, The skill task rejection
path in task_executor.py only reports through progress_callback, so add an
explicit logging call in the task_type == "skill" branch before returning. Use
the existing task executor logger in task_executor and include the same
skill-generation/TE_RUN_MODE=0 message so this new blocking flow is visible in
application logs and observability tools.

Source: Coding guidelines

🤖 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/wiki.py`:
- Around line 400-404: The claim prompt hint construction in
`_wiki_template_fields()` is using the wrong keys, so `claim_subject` stays
empty and the custom claim schema never reaches the prompt. Update the claim
hint generation near `claim_statement` and `claim_subject` to read from the
field dictionaries’ `name` and `description` values (instead of `subject`), and
make sure the resulting hints are derived from the actual config shape returned
by `_wiki_template_fields()`.
- Around line 2664-2667: The fallback in _wiki_load_chunks_by_id handling is
using print to emit chunk_ids, tenant_id, and kb_id, which bypasses the module’s
logging conventions. Replace that stdout output with structured logging via
logging.warning(...) or logging.exception(...) in the chunk_map check path,
keeping the existing return fallback unchanged and using _wiki_load_chunks_by_id
/ chunk_map as the key locations to update.

---

Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/wiki.py`:
- Around line 88-93: The prompt strings in WIKI_MAP_SYSTEM and the other
affected prompt blocks use adjacent literals that concatenate without
whitespace, so separate the sentences with an explicit space or newline in each
multi-line prompt definition. Update the prompt assembly in the identified
constants/helpers so the final text remains readable and the model receives
clean sentence boundaries, especially around the schema/JSON instructions and
the language-preservation note.
- Around line 1695-1797: The reconciliation map is keyed only by the bare item
name, so a concept and entity with the same display string can overwrite each
other and skip MAYBE/UPDATE handling. Update the reconciliation logic in the
function that builds this map so each entry is keyed by both kind and name (or
use a nested structure), and make sure the downstream consumers that read this
map, including _wiki_resolve_maybe_items and _wiki_planning_call, are updated to
use the same composite key shape.

---

Nitpick comments:
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 562-830: The new artifact/skill handlers repeat the same
try/success/except response handling pattern, so extract the shared flow into a
reusable helper or decorator. Use the existing endpoint functions like
has_any_wiki, list_wiki_pages, get_wiki_graph, clear_wiki, get_wiki_page,
has_any_skill, get_skill_tree, get_skill_page, list_wiki_commits,
get_wiki_commit, and update_wiki_page as callers of a common wrapper that logs
exceptions and maps service results to get_result/get_error_data_result.
- Around line 589-593: The pagination parsing in dataset_api’s request handling
accepts 0 and negative values for page and page_size because it only casts with
int after request.args.get; update the validation in the affected pagination
blocks (including the shared logic used in the other matching location) to
reject values less than 1 and return get_error_argument_result when page or
page_size is not a positive integer. Use the existing page/page_size parsing in
the dataset API methods as the place to enforce the lower bound before passing
values into downstream pagination/service calls.

In `@rag/svr/task_executor.py`:
- Around line 1544-1546: The skill task rejection path in task_executor.py only
reports through progress_callback, so add an explicit logging call in the
task_type == "skill" branch before returning. Use the existing task executor
logger in task_executor and include the same skill-generation/TE_RUN_MODE=0
message so this new blocking flow is visible in application logs and
observability tools.
🪄 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: 0a015078-53df-4c84-8574-dfb039a90bc3

📥 Commits

Reviewing files that changed from the base of the PR and between 5124e44 and a645d96.

📒 Files selected for processing (13)
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • api/db/services/dialog_service.py
  • rag/advanced_rag/knowlege_compile/__init__.py
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/mind_map_extractor.py
  • rag/advanced_rag/knowlege_compile/raptor.py
  • rag/advanced_rag/knowlege_compile/wiki.py
  • rag/svr/task_executor.py
  • rag/svr/task_executor_refactor/raptor_service.py
  • rag/svr/task_executor_refactor/task_handler.py
  • test/unit_test/rag/graphrag/test_checkpoint_resume.py
  • test/unit_test/rag/test_raptor_psi_tree_builder.py
💤 Files with no reviewable changes (2)
  • rag/advanced_rag/knowlege_compile/mind_map_extractor.py
  • rag/advanced_rag/knowlege_compile/raptor.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/svr/task_executor_refactor/raptor_service.py
  • api/apps/services/dataset_api_service.py

Comment on lines +2664 to +2667
chunk_map = await _wiki_load_chunks_by_id(chunk_ids, tenant_id, kb_id)
if not chunk_map:
print("chunk_map::::::::::::::", chunk_ids, tenant_id, kb_id, flush=True)
return "(source chunks could not be loaded)"

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use structured logging instead of print.

The fallback path leaks identifiers to stdout and bypasses the file's logging conventions. Switch this to logging.warning(...) or logging.exception(...). As per coding guidelines: **/*.py: Add logging for new flows.

🤖 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/wiki.py` around lines 2664 - 2667, The
fallback in _wiki_load_chunks_by_id handling is using print to emit chunk_ids,
tenant_id, and kb_id, which bypasses the module’s logging conventions. Replace
that stdout output with structured logging via logging.warning(...) or
logging.exception(...) in the chunk_map check path, keeping the existing return
fallback unchanged and using _wiki_load_chunks_by_id / chunk_map as the key
locations to update.

Source: Coding guidelines

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
rag/svr/task_executor_refactor/task_handler.py (4)

460-506: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Update RAPTOR document stats per output document.

run_raptor_for_kb() is called with ctx.doc_ids or [ctx.doc_id], and the code already builds raptor_doc_ids, but DocumentService.increment_chunk_num() credits all chunks/tokens to only the first doc id. For multi-doc RAPTOR runs, other docs get stale counts and the first doc is over-counted.

🤖 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/task_handler.py` around lines 460 - 506, The
RAPTOR stats update in task_handler.py currently credits all chunks and tokens
to only the first document via task_doc_id, even though run_raptor_for_kb() can
process multiple doc_ids and raptor_doc_ids is already derived. Update the
DocumentService.increment_chunk_num path so counts are applied per output
document, using the chunk doc_id grouping for each RAPTOR doc instead of a
single shared doc id, and keep the write_interceptor branch aligned with the
same per-doc behavior.

1260-1286: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Select marker fields before filtering generated rows.

Both loaders check compile_kwd, but neither selects it, so the filter is a no-op when get_fields() returns only requested fields. Include compile_kwd and raptor_kwd, then skip generated structure/artifact/RAPTOR rows before feeding compilation flows.

Proposed fix
-        select_fields = ["id", "doc_id", "content_with_weight", vctr_nm]
+        select_fields = ["id", "doc_id", "content_with_weight", vctr_nm, "compile_kwd", "raptor_kwd"]
...
-                if row.get("compile_kwd"):
+                if row.get("compile_kwd") or row.get("raptor_kwd"):
                     continue
         select_fields = [
             "id", "doc_id", "content_with_weight",
-            "page_num_int", "top_int",
+            "page_num_int", "top_int", "compile_kwd", "raptor_kwd",
         ]
...
-                if row.get("compile_kwd"):
+                if row.get("compile_kwd") or row.get("raptor_kwd"):
                     continue

Also applies to: 1825-1852

🤖 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/task_handler.py` around lines 1260 - 1286,
Select marker fields before filtering generated rows: in the chunk-loading logic
around the tree-template path in task_handler.py, the code checks compile_kwd
but does not request it from settings.docStoreConn.get_fields(), so the filter
never works. Update the select_fields used by the search/get_fields flow (and
the matching loader around the other referenced range) to include both
compile_kwd and raptor_kwd, then keep the existing row-skipping checks so
generated structure/artifact/RAPTOR rows are excluded before entering the
compilation flow.

1493-1523: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Only rewrite and soft-delete clusters whose merged row was inserted.

After vector casting, merged_rows is filtered, but cluster_new_id still contains every planned replacement. A cast failure or short embedding result can make the tree point to a non-inserted chunk and soft-delete the original source chunks.

Proposed fix direction
         merged_rows = [r for r in merged_rows if r.get(vctr_nm) is not None]
         if not merged_rows:
             return
+        inserted_new_ids = {r["id"] for r in merged_rows}
...
-        for node_id_int, new_chunk_id in cluster_new_id.items():
+        for node_id_int, new_chunk_id in cluster_new_id.items():
+            if new_chunk_id not in inserted_new_ids:
+                continue
             node, _ = cluster_id_map[node_id_int]
...
-        for node_id_int, new_chunk_id in cluster_new_id.items():
+        for node_id_int, new_chunk_id in cluster_new_id.items():
+            if new_chunk_id not in inserted_new_ids:
+                continue
             _, src_ids = cluster_id_map[node_id_int]

Also applies to: 1527-1540

🤖 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/task_handler.py` around lines 1493 - 1523, The
rechunk flow in task_handler.py is updating and soft-deleting every planned
cluster replacement even after some merged_rows were dropped by vector casting,
so only successfully inserted chunks should be propagated. In the block around
the merged_rows/vector casting loop and the later cluster rewrite in the same
task handler, filter or rebuild cluster_new_id (and any related source_chunk_ids
updates) to include only rows that survived the insert path, then skip
rewrite/soft-delete for missing replacements. Use the existing symbols
merged_rows, cluster_new_id, cluster_id_map, and the insert call in the rechunk
section to keep tree updates aligned with actually inserted chunks.

1071-1083: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not key tree graph nodes by title.

The docstring promises stable generated node ids, but node_id = title collapses duplicate or empty titles into the same graph node and creates ambiguous edges. Use _next_id() for relation endpoints and keep the title as display metadata.

🤖 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/task_handler.py` around lines 1071 - 1083, The
tree graph node identity in _walk is incorrectly derived from title, which
causes duplicate or empty titles to merge into the same node. Update the node_id
assignment to use the stable generated ID from _next_id() instead, and keep
title only as metadata for display on the node object. Make sure any relation
endpoints built in _walk continue to reference these generated ids so edges
remain unambiguous and stable.
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/dataset_skill_generator.py (1)

135-135: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clean up the Ruff violations in the new module.

Bind level before the nested cluster summarizer, use zip(..., strict=True), and narrow or explicitly justify the broad delete exception. As per coding guidelines, use ruff for Python linting and formatting with commands ruff check and ruff format.

Also applies to: 431-453, 493-493, 515-515

🤖 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_skill_generator.py` at line 135, Clean
up the Ruff violations in the new dataset skill generator module by fixing the
scope of level before the nested cluster summarizer, updating any multi-iterator
unpacking to use zip(..., strict=True), and replacing the broad delete exception
with a narrower exception type or an explicit justification where the delete
occurs. Review the affected code paths around the nested summarizer and the
delete handling, then run ruff check and ruff format to verify the module is
lint- and format-clean.

Sources: Coding guidelines, 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/svr/task_executor_refactor/dataset_skill_generator.py`:
- Around line 321-536: run_corpus2skill continues expensive
summarization/clustering and ES writes even after cancellation. Add
ctx.has_canceled_func(ctx.id) checks at the phase boundaries in
run_corpus2skill, especially after loading docs, after leaf summaries, after
clustering/labeling, and immediately before the delete/insert block. If
canceled, stop early and return without calling settings.docStoreConn.delete or
settings.docStoreConn.insert.
- Around line 260-275: The skill row identity in skill_node_es_row is colliding
because it hashes only node.folder_name, which is not unique across branches.
Update _assign_folders to carry a full path value for each SkillNode (for
example a path_name built from parent path plus the local folder), then use that
path-based identifier in skill_node_es_row for row_id and any child references
that need unique tree identity. Keep folder_name as the local label if needed,
but make ES identity and tree traversal keys rely on the full path to avoid
ambiguous duplicates.

---

Outside diff comments:
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 460-506: The RAPTOR stats update in task_handler.py currently
credits all chunks and tokens to only the first document via task_doc_id, even
though run_raptor_for_kb() can process multiple doc_ids and raptor_doc_ids is
already derived. Update the DocumentService.increment_chunk_num path so counts
are applied per output document, using the chunk doc_id grouping for each RAPTOR
doc instead of a single shared doc id, and keep the write_interceptor branch
aligned with the same per-doc behavior.
- Around line 1260-1286: Select marker fields before filtering generated rows:
in the chunk-loading logic around the tree-template path in task_handler.py, the
code checks compile_kwd but does not request it from
settings.docStoreConn.get_fields(), so the filter never works. Update the
select_fields used by the search/get_fields flow (and the matching loader around
the other referenced range) to include both compile_kwd and raptor_kwd, then
keep the existing row-skipping checks so generated structure/artifact/RAPTOR
rows are excluded before entering the compilation flow.
- Around line 1493-1523: The rechunk flow in task_handler.py is updating and
soft-deleting every planned cluster replacement even after some merged_rows were
dropped by vector casting, so only successfully inserted chunks should be
propagated. In the block around the merged_rows/vector casting loop and the
later cluster rewrite in the same task handler, filter or rebuild cluster_new_id
(and any related source_chunk_ids updates) to include only rows that survived
the insert path, then skip rewrite/soft-delete for missing replacements. Use the
existing symbols merged_rows, cluster_new_id, cluster_id_map, and the insert
call in the rechunk section to keep tree updates aligned with actually inserted
chunks.
- Around line 1071-1083: The tree graph node identity in _walk is incorrectly
derived from title, which causes duplicate or empty titles to merge into the
same node. Update the node_id assignment to use the stable generated ID from
_next_id() instead, and keep title only as metadata for display on the node
object. Make sure any relation endpoints built in _walk continue to reference
these generated ids so edges remain unambiguous and stable.

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_skill_generator.py`:
- Line 135: Clean up the Ruff violations in the new dataset skill generator
module by fixing the scope of level before the nested cluster summarizer,
updating any multi-iterator unpacking to use zip(..., strict=True), and
replacing the broad delete exception with a narrower exception type or an
explicit justification where the delete occurs. Review the affected code paths
around the nested summarizer and the delete handling, then run ruff check and
ruff format to verify the module is lint- and format-clean.
🪄 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: bafbcae4-1ff8-41f0-81fa-cd6accbcf0f6

📥 Commits

Reviewing files that changed from the base of the PR and between a645d96 and 6af98a6.

📒 Files selected for processing (5)
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/advanced_rag/knowlege_compile/wiki.py
  • rag/svr/task_executor_refactor/dataset_skill_generator.py
  • rag/svr/task_executor_refactor/task_handler.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/advanced_rag/knowlege_compile/_common.py

Comment on lines +260 to +275
def skill_node_es_row(ctx: TaskContext, node: "SkillNode") -> Dict:
"""Build the ES row for one tree node. Stable id from
(kb_id, folder_name) so re-runs upsert cleanly."""
kb_id_str = str(ctx.kb_id)
row_id = xxhash.xxh64(
f"skill:{kb_id_str}:{node.folder_name}".encode("utf-8", "surrogatepass"),
).hexdigest()
return {
"id": row_id,
"kb_id": kb_id_str,
"doc_id": kb_id_str, # KB-scoped sentinel
"compile_kwd": "skill",
"skill_kwd": node.folder_name,
"depth_int": int(node.level),
"children_kwd": [c.folder_name for c in node.children],
"source_doc_ids": list(node.doc_ids),

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use a full tree path for skill row identity.

row_id is based only on node.folder_name, but deeper nodes are named only by local sibling position (group-00-*, group-01-*). Two branches can produce the same folder name, causing ES id collisions and ambiguous children_kwd.

Suggested direction
-        "skill_kwd": node.folder_name,
+        "skill_kwd": node.path_name,
...
-        "children_kwd": [c.folder_name for c in node.children],
+        "children_kwd": [c.path_name for c in node.children],

Assign path_name during _assign_folders, e.g. skill-00-foo/group-00-bar, and hash that path instead of the local folder name.

Also applies to: 499-506

🤖 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_skill_generator.py` around lines 260 -
275, The skill row identity in skill_node_es_row is colliding because it hashes
only node.folder_name, which is not unique across branches. Update
_assign_folders to carry a full path value for each SkillNode (for example a
path_name built from parent path plus the local folder), then use that
path-based identifier in skill_node_es_row for row_id and any child references
that need unique tree identity. Keep folder_name as the local label if needed,
but make ES identity and tree traversal keys rely on the full path to avoid
ambiguous duplicates.

@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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
rag/svr/task_executor_refactor/task_handler.py (5)

1074-1087: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use generated node IDs instead of titles for tree graph identity.

title is not unique or guaranteed non-empty, so using it as node_id can collapse multiple nodes into the same entity/relation key. Keep the title as display metadata and use _next_id() for graph identity.

Proposed change
-            title = node.get("title") or ""
-            node_id = title `#_next_id`()
+            title = str(node.get("title") or "").strip()
+            node_id = _next_id()
             ent: dict = {
                 "name": node_id,
+                "title": title or node_id,
                 "type": "tree_node",
-                "description": node.get("description", title),
+                "description": node.get("description") or title or node_id,
                 "mention_count": 1,
             }
🤖 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/task_handler.py` around lines 1074 - 1087, The
tree graph identity in the node-building logic is currently using title as
node_id, which can merge distinct nodes when titles repeat or are empty. Update
the entity/relation creation in task_handler’s tree node handling to use
_next_id() for node_id while keeping title only as display metadata in the
entity fields. Make sure the child relation in the same block uses the generated
node_id so each tree node remains uniquely identifiable.

1253-1279: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Select compile_kwd before filtering compiled rows.

Both loaders intend to skip compiled/artifact rows, but compile_kwd is not in select_fields, so row.get("compile_kwd") is always empty and compiled rows can be reprocessed as source chunks.

Proposed change
-        select_fields = ["id", "doc_id", "content_with_weight", vctr_nm]
+        select_fields = ["id", "doc_id", "content_with_weight", vctr_nm, "compile_kwd"]
         select_fields = [
             "id", "doc_id", "content_with_weight",
-            "page_num_int", "top_int",
+            "page_num_int", "top_int", "compile_kwd",
         ]

Also applies to: 1564-1591

🤖 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/task_handler.py` around lines 1253 - 1279, The
chunk-loading logic in the loader path that builds `select_fields` and iterates
`field_map` is checking `row.get("compile_kwd")` without actually selecting that
field, so compiled rows are never filtered out. Update the relevant loader(s)
around the `select_fields`/`settings.docStoreConn.get_fields` flow to include
`compile_kwd` in the requested fields before the `for row_id, row in
field_map.items()` loop, so the existing skip condition can work correctly in
both affected implementations.

1486-1524: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Only rewrite and soft-delete clusters whose merged rows were inserted.

cluster_new_id still contains clusters whose rows are later dropped by vector conversion/filtering. Those clusters can be rewritten to missing chunk IDs and their original chunks soft-deleted.

Proposed change
         merged_rows = [r for r in merged_rows if r.get(vctr_nm) is not None]
         if not merged_rows:
             return
+        inserted_new_ids = {str(r.get("id")) for r in merged_rows if r.get("id")}

         # --- 5. Insert merged, rewrite tree, soft-delete originals ---
         try:
             await thread_pool_exec(
                 settings.docStoreConn.insert, merged_rows, index_nm, ctx.kb_id,
@@
         # leaves the tree pointing at the still-active originals.
         for node_id_int, new_chunk_id in cluster_new_id.items():
+            if new_chunk_id not in inserted_new_ids:
+                continue
             node, _ = cluster_id_map[node_id_int]
             node["source_chunk_ids"] = [new_chunk_id]
@@
         # traceability so audit queries can still tell what replaced it.
         for node_id_int, new_chunk_id in cluster_new_id.items():
+            if new_chunk_id not in inserted_new_ids:
+                continue
             _, src_ids = cluster_id_map[node_id_int]
🤖 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/task_handler.py` around lines 1486 - 1524,
`cluster_new_id` can still include clusters whose merged rows are removed before
insert, so `source_chunk_ids` rewriting and soft-delete logic in
`task_handler.py` must only run for clusters that actually produced an inserted
row. Update the merge flow around the vector casting/filtering and the
`thread_pool_exec(settings.docStoreConn.insert, ...)` insert so you track the
successfully retained cluster IDs, then use that filtered set for the later
rewrite loop and soft-delete loop. Keep the existing `cluster_new_id`,
`cluster_id_map`, and insert/soft-delete sections aligned so dropped clusters
are skipped entirely.

455-499: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Gate RAPTOR cleanup/stats on successful insert and update stats per doc_id.

When insert_chunks returns false, this still runs stale cleanup, graph persistence, and DocumentService.increment_chunk_num, then can mark RAPTOR done. Also, multi-doc RAPTOR chunks are later grouped by actual chunk["doc_id"], but stats are applied only to the first ctx.doc_ids entry.

Proposed change direction
 insert_result = await chunk_service.insert_chunks(ctx.id, task_tenant_id, task_dataset_id, chunks)
 if insert_result:
     ctx.recording_context.record("insertion_result", "success")
 else:
     ctx.recording_context.record("insertion_result", "failed")
+    ctx.progress_cb(prog=-1.0, msg="Failed to insert RAPTOR chunks")
+    return

Then group successful chunks by doc_id before calling DocumentService.increment_chunk_num; if per-doc token counts are not available on chunks, return them from run_raptor_for_kb instead of assigning the aggregate token_count to the first doc.

🤖 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/task_handler.py` around lines 455 - 499, Gate
the RAPTOR cleanup, graph persistence, and document-stat updates in task_handler
after the insert_chunks call in this flow so they only run when
ChunkService.insert_chunks succeeds; otherwise skip the downstream work and
avoid marking RAPTOR complete on a failed insert. Also update the
DocumentService.increment_chunk_num path to operate per actual chunk doc_id
instead of only task_doc_id, by grouping the inserted chunks by their
chunk["doc_id"] in run_raptor_for_kb and passing per-doc token counts through to
the stats update. Use the existing symbols insert_chunks, _delete_raptor_chunks,
_persist_raptor_graph_to_es, and DocumentService.increment_chunk_num to locate
the affected logic.

868-889: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Close the cached LLMBundle instances
LLMBundle.close() releases Langfuse and model resources, but this branch never enters/exits or closes llm_bundle_cache. Wrap the cache in a try/finally or ExitStack and close each bundle on exit.

🤖 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/task_handler.py` around lines 868 - 889, The
`llm_bundle_cache` in `task_handler.py` is never cleaned up, so cached
`LLMBundle` instances can leak Langfuse and model resources. Update the
`document_structure_compile` branch around `llm_bundle_cache`,
`chat_mdl_by_tid`, and `filtered_templates` to ensure every created `LLMBundle`
is closed on exit, even when exceptions or early continues occur. Use a
`try/finally` or `ExitStack` around the cache lifecycle and close each bundle in
`llm_bundle_cache` before returning from this block.
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/task_handler.py (1)

304-311: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a dispatch log for the new artifact flow.

Log the task/kb/doc identifiers before calling run_wiki so this new route is observable in production. As per coding guidelines, **/*.py: Add logging for new flows.

Proposed change
 elif task_type == "artifact":
     from rag.svr.task_executor_refactor.dataset_wiki_generator import (
         run_wiki,
     )
+    logging.info(
+        "Starting artifact generation task=%s kb=%s doc=%s",
+        ctx.id,
+        ctx.kb_id,
+        ctx.doc_id,
+    )
     await run_wiki(
         self._task_context,
         embedding_model,
🤖 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/task_handler.py` around lines 304 - 311, Add a
dispatch log for the new wiki artifact flow in task_handler’s run_wiki path.
Before calling run_wiki in the task dispatch code, log the current task,
knowledge base, and document identifiers from self._task_context so this route
is visible in production. Use the existing task_handler flow around run_wiki to
place the log right before the await call, and keep the message specific to the
artifact/wiki dispatch.

Source: Coding guidelines

🤖 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/dataset_wiki_generator.py`:
- Around line 166-184: During full regeneration in dataset_wiki_generator.py,
the replacement insert updates current pages but leaves obsolete artifact_page
records behind, so stale slugs still show up in the Artifact tab. In the
regeneration flow around the prior-by-slug lookup and bulk upsert, add a cleanup
step after the insert succeeds that compares the existing artifact_page rows
against the new refined page slug set and deletes any rows whose slug is no
longer present. Use the existing page-processing path and identifiers like
target_slugs, prior_by_slug, and the artifact_page compile_kwd query to locate
where to track and remove the stale rows.
- Around line 206-222: The persistence path in persist_wiki_pages_to_es is
swallowing embedding/insert failures and run_wiki still continues to write graph
rows and report success. Update persist_wiki_pages_to_es to surface failures
back to its caller instead of just logging and returning, then have run_wiki
check that result and skip graph-row writes plus success reporting when
artifact-page persistence fails. Also apply the same failure
propagation/guarding to the related retry or batch paths referenced by the other
impacted sections so stale or missing artifact_page rows cannot be treated as a
successful run.
- Around line 469-507: The graph replacement flow in _replace_bucket should not
continue to insert after a delete failure for artifact_entity or
artifact_relation. Update this helper so delete errors are surfaced or retried
instead of being swallowed by the broad except that logs “relying on id-upsert,”
and keep the insert path only after a successful delete. Review the broad
catches in _replace_bucket and _sweep_legacy_blob as well, and narrow them or
add an explicit justification if they must remain.
- Around line 733-739: The REDUCE stage in wiki_reduce_from_extracts is still
reading all artifact_map_extract rows, so stale extracts from ineligible docs
can continue affecting output. Update the wiki generation flow around
dataset_wiki_generator.py and wiki_reduce_from_extracts to either pass the
current eligible document IDs into REDUCE and filter the input, or delete/prune
outdated MAP rows when eligibility changes. Make sure the fix is applied at the
call site where wiki_reduce_from_extracts is invoked and in the corresponding
data aggregation logic so only eligible docs contribute.
- Line 225: The iteration in the dataset wiki generator uses zip(pages,
embeddings) without an explicit strict contract, which Ruff B905 flags even with
the prior length check. Update the loop in the page/embedding pairing logic to
use zip(..., strict=True) so the invariant is enforced directly and the intent
is clear.

---

Outside diff comments:
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 1074-1087: The tree graph identity in the node-building logic is
currently using title as node_id, which can merge distinct nodes when titles
repeat or are empty. Update the entity/relation creation in task_handler’s tree
node handling to use _next_id() for node_id while keeping title only as display
metadata in the entity fields. Make sure the child relation in the same block
uses the generated node_id so each tree node remains uniquely identifiable.
- Around line 1253-1279: The chunk-loading logic in the loader path that builds
`select_fields` and iterates `field_map` is checking `row.get("compile_kwd")`
without actually selecting that field, so compiled rows are never filtered out.
Update the relevant loader(s) around the
`select_fields`/`settings.docStoreConn.get_fields` flow to include `compile_kwd`
in the requested fields before the `for row_id, row in field_map.items()` loop,
so the existing skip condition can work correctly in both affected
implementations.
- Around line 1486-1524: `cluster_new_id` can still include clusters whose
merged rows are removed before insert, so `source_chunk_ids` rewriting and
soft-delete logic in `task_handler.py` must only run for clusters that actually
produced an inserted row. Update the merge flow around the vector
casting/filtering and the `thread_pool_exec(settings.docStoreConn.insert, ...)`
insert so you track the successfully retained cluster IDs, then use that
filtered set for the later rewrite loop and soft-delete loop. Keep the existing
`cluster_new_id`, `cluster_id_map`, and insert/soft-delete sections aligned so
dropped clusters are skipped entirely.
- Around line 455-499: Gate the RAPTOR cleanup, graph persistence, and
document-stat updates in task_handler after the insert_chunks call in this flow
so they only run when ChunkService.insert_chunks succeeds; otherwise skip the
downstream work and avoid marking RAPTOR complete on a failed insert. Also
update the DocumentService.increment_chunk_num path to operate per actual chunk
doc_id instead of only task_doc_id, by grouping the inserted chunks by their
chunk["doc_id"] in run_raptor_for_kb and passing per-doc token counts through to
the stats update. Use the existing symbols insert_chunks, _delete_raptor_chunks,
_persist_raptor_graph_to_es, and DocumentService.increment_chunk_num to locate
the affected logic.
- Around line 868-889: The `llm_bundle_cache` in `task_handler.py` is never
cleaned up, so cached `LLMBundle` instances can leak Langfuse and model
resources. Update the `document_structure_compile` branch around
`llm_bundle_cache`, `chat_mdl_by_tid`, and `filtered_templates` to ensure every
created `LLMBundle` is closed on exit, even when exceptions or early continues
occur. Use a `try/finally` or `ExitStack` around the cache lifecycle and close
each bundle in `llm_bundle_cache` before returning from this block.

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 304-311: Add a dispatch log for the new wiki artifact flow in
task_handler’s run_wiki path. Before calling run_wiki in the task dispatch code,
log the current task, knowledge base, and document identifiers from
self._task_context so this route is visible in production. Use the existing
task_handler flow around run_wiki to place the log right before the await call,
and keep the message specific to the artifact/wiki dispatch.
🪄 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: 266be37c-08db-4421-ae4b-7c5cdc1fc4d4

📥 Commits

Reviewing files that changed from the base of the PR and between 6af98a6 and c644ad6.

📒 Files selected for processing (2)
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
  • rag/svr/task_executor_refactor/task_handler.py

Comment on lines +166 to +184
# Capture the prior rendered content for every slug we're about to
# overwrite, so the per-page commit row downstream has a real diff
# baseline. Single batch read by slug_kwd IN [...] — one round-trip
# regardless of page count. Failures here degrade gracefully.
target_slugs: list[str] = [
(p.get("slug") or "").strip()
for p in pages
if isinstance(p.get("slug"), str) and p.get("slug")
]
prior_by_slug: dict[str, str] = {}
if target_slugs:
try:
res = await thread_pool_exec(
settings.docStoreConn.search,
["id", "slug_kwd", "content_with_weight"], [],
{"compile_kwd": ["artifact_page"], "slug_kwd": list(target_slugs)},
[], OrderByExpr(),
0, max(len(target_slugs), 1),
index, [ctx.kb_id],

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Remove stale artifact_page rows during full regeneration.

The insert overwrites current slugs, but pages that disappear or are renamed are never removed. Since the Artifact tab reads all compile_kwd="artifact_page" rows, stale pages can remain visible after a full compile. Track existing page slugs and delete rows not present in the new refined page set after the replacement insert succeeds.

Also applies to: 283-284

🤖 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 166 -
184, During full regeneration in dataset_wiki_generator.py, the replacement
insert updates current pages but leaves obsolete artifact_page records behind,
so stale slugs still show up in the Artifact tab. In the regeneration flow
around the prior-by-slug lookup and bulk upsert, add a cleanup step after the
insert succeeds that compares the existing artifact_page rows against the new
refined page slug set and deletes any rows whose slug is no longer present. Use
the existing page-processing path and identifiers like target_slugs,
prior_by_slug, and the artifact_page compile_kwd query to locate where to track
and remove the stale rows.

Comment on lines +206 to +222
try:
embeddings, _ = await thread_pool_exec(embd_mdl.encode, embed_inputs)
except Exception:
logging.exception(
"wiki_persist: summary embedding batch failed for kb=%s", kb_id_str,
)
return
try:
n_emb = len(embeddings) if embeddings is not None else 0
except TypeError:
n_emb = 0
if n_emb != len(pages):
logging.warning(
"artifact_persist: embedding count %d != pages %d for kb=%s; aborting",
n_emb, len(pages), kb_id_str,
)
return

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Surface artifact-page persistence failures before reporting success.

persist_wiki_pages_to_es logs and returns on embedding/insert failure, but run_wiki still writes graph rows and reports success. That can leave canvas nodes pointing to missing or stale artifact_page rows consumed by the dataset API.

Proposed fix
 async def persist_wiki_pages_to_es(
     ctx: TaskContext, pages: List[Dict], embd_mdl,
-) -> None:
+) -> bool:
@@
     if not pages:
-        return
+        return True
@@
     except Exception:
         logging.exception(
             "wiki_persist: summary embedding batch failed for kb=%s", kb_id_str,
         )
-        return
+        return False
@@
     if n_emb != len(pages):
         logging.warning(
             "artifact_persist: embedding count %d != pages %d for kb=%s; aborting",
             n_emb, len(pages), kb_id_str,
         )
-        return
+        return False
@@
     if not rows:
-        return
+        return False
@@
     except Exception:
         logging.exception(
             "wiki_persist: bulk insert failed for kb=%s (rows=%d)",
             kb_id_str, len(rows),
         )
-        return
+        return False
@@
             logging.exception(
                 "wiki_persist: commit record failed for kb=%s slug=%s",
                 kb_id_str, slug,
             )
+    return True
@@
     # 6. Persist searchable artifact_page rows.
     try:
-        await persist_wiki_pages_to_es(ctx, pages or [], embedding_model)
+        pages_persisted = await persist_wiki_pages_to_es(ctx, pages or [], embedding_model)
     except Exception:
         logging.exception("wiki: ES persist failed for kb %s", ctx.kb_id)
+        progress(-1, "Wiki page persistence failed.")
+        return
+    if not pages_persisted:
+        progress(-1, "Wiki page persistence failed.")
+        return

Also applies to: 283-290, 766-778

🤖 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 206 -
222, The persistence path in persist_wiki_pages_to_es is swallowing
embedding/insert failures and run_wiki still continues to write graph rows and
report success. Update persist_wiki_pages_to_es to surface failures back to its
caller instead of just logging and returning, then have run_wiki check that
result and skip graph-row writes plus success reporting when artifact-page
persistence fails. Also apply the same failure propagation/guarding to the
related retry or batch paths referenced by the other impacted sections so stale
or missing artifact_page rows cannot be treated as a successful run.

return

rows: List[Dict] = []
for page, vec in zip(pages, embeddings):

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the target file around the cited line and confirm surrounding context.
file='rag/svr/task_executor_refactor/dataset_wiki_generator.py'
wc -l "$file"
sed -n '200,240p' "$file"

# Check whether Ruff B905 would be applicable from the code pattern alone.
python3 - <<'PY'
from pathlib import Path
p = Path('rag/svr/task_executor_refactor/dataset_wiki_generator.py')
text = p.read_text()
for i, line in enumerate(text.splitlines(), 1):
    if 'zip(pages, embeddings)' in line:
        print(f'zip call at line {i}: {line.strip()}')
PY

Repository: infiniflow/ragflow

Length of output: 1713


Make the zip() invariant explicit
zip(pages, embeddings) should use strict=True here; the length check above doesn’t satisfy Ruff B905, and this keeps the iteration contract explicit.

Proposed fix
-    for page, vec in zip(pages, embeddings):
+    for page, vec in zip(pages, embeddings, strict=True):
📝 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.

Suggested change
for page, vec in zip(pages, embeddings):
for page, vec in zip(pages, embeddings, strict=True):
🧰 Tools
🪛 Ruff (0.15.20)

[warning] 225-225: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)

🤖 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 225, The
iteration in the dataset wiki generator uses zip(pages, embeddings) without an
explicit strict contract, which Ruff B905 flags even with the prior length
check. Update the loop in the page/embedding pairing logic to use zip(...,
strict=True) so the invariant is enforced directly and the intent is clear.

Sources: Coding guidelines, Linters/SAST tools

Comment on lines +469 to +507
async def _replace_bucket(kwd: str, rows: List[Dict]) -> None:
try:
await thread_pool_exec(
settings.docStoreConn.delete,
{"compile_kwd": kwd}, index, ctx.kb_id,
)
except Exception:
logging.debug(
"%s: prior delete failed; relying on id-upsert", kwd,
)
if not rows:
return
try:
await thread_pool_exec(
settings.docStoreConn.insert, rows, index, ctx.kb_id,
)
except Exception:
logging.exception(
"%s: insert failed for kb=%s (%d rows)", kwd, kb_id_str, len(rows),
)

async def _sweep_legacy_blob() -> None:
try:
await thread_pool_exec(
settings.docStoreConn.delete,
{"compile_kwd": "artifact_page_graph"},
index, ctx.kb_id,
)
except Exception:
logging.debug(
"artifact_page_graph: legacy blob sweep failed for kb=%s",
kb_id_str,
)

await asyncio.gather(
_replace_bucket("artifact_entity", entity_rows),
_replace_bucket("artifact_relation", relation_rows),
_sweep_legacy_blob(),
)

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not continue graph replacement after a bucket delete failure.

If the artifact_entity or artifact_relation delete fails, inserting new rows cannot remove deleted/renamed nodes and edges. Surface the failure or retry instead of relying on id-upsert; also narrow or explicitly justify the Ruff BLE001 blind catches.

Proposed direction
         try:
             await thread_pool_exec(
                 settings.docStoreConn.delete,
                 {"compile_kwd": kwd}, index, ctx.kb_id,
             )
         except Exception:
-            logging.debug(
-                "%s: prior delete failed; relying on id-upsert", kwd,
-            )
+            logging.exception("%s: prior delete failed for kb=%s", kwd, kb_id_str)
+            raise
📝 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.

Suggested change
async def _replace_bucket(kwd: str, rows: List[Dict]) -> None:
try:
await thread_pool_exec(
settings.docStoreConn.delete,
{"compile_kwd": kwd}, index, ctx.kb_id,
)
except Exception:
logging.debug(
"%s: prior delete failed; relying on id-upsert", kwd,
)
if not rows:
return
try:
await thread_pool_exec(
settings.docStoreConn.insert, rows, index, ctx.kb_id,
)
except Exception:
logging.exception(
"%s: insert failed for kb=%s (%d rows)", kwd, kb_id_str, len(rows),
)
async def _sweep_legacy_blob() -> None:
try:
await thread_pool_exec(
settings.docStoreConn.delete,
{"compile_kwd": "artifact_page_graph"},
index, ctx.kb_id,
)
except Exception:
logging.debug(
"artifact_page_graph: legacy blob sweep failed for kb=%s",
kb_id_str,
)
await asyncio.gather(
_replace_bucket("artifact_entity", entity_rows),
_replace_bucket("artifact_relation", relation_rows),
_sweep_legacy_blob(),
)
async def _replace_bucket(kwd: str, rows: List[Dict]) -> None:
try:
await thread_pool_exec(
settings.docStoreConn.delete,
{"compile_kwd": kwd}, index, ctx.kb_id,
)
except Exception:
logging.exception("%s: prior delete failed for kb=%s", kwd, kb_id_str)
raise
if not rows:
return
try:
await thread_pool_exec(
settings.docStoreConn.insert, rows, index, ctx.kb_id,
)
except Exception:
logging.exception(
"%s: insert failed for kb=%s (%d rows)", kwd, kb_id_str, len(rows),
)
async def _sweep_legacy_blob() -> None:
try:
await thread_pool_exec(
settings.docStoreConn.delete,
{"compile_kwd": "artifact_page_graph"},
index, ctx.kb_id,
)
except Exception:
logging.debug(
"artifact_page_graph: legacy blob sweep failed for kb=%s",
kb_id_str,
)
await asyncio.gather(
_replace_bucket("artifact_entity", entity_rows),
_replace_bucket("artifact_relation", relation_rows),
_sweep_legacy_blob(),
)
🧰 Tools
🪛 Ruff (0.15.20)

[warning] 475-475: Do not catch blind exception: Exception

(BLE001)


[warning] 497-497: Do not catch blind exception: Exception

(BLE001)

🤖 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 469 -
507, The graph replacement flow in _replace_bucket should not continue to insert
after a delete failure for artifact_entity or artifact_relation. Update this
helper so delete errors are surfaced or retried instead of being swallowed by
the broad except that logs “relying on id-upsert,” and keep the insert path only
after a successful delete. Review the broad catches in _replace_bucket and
_sweep_legacy_blob as well, and narrow them or add an explicit justification if
they must remain.

Source: Linters/SAST tools

Comment on lines +733 to +739
await wiki_reduce_from_extracts(
chat_mdl=kb_chat_mdl,
embd_mdl=embedding_model,
tenant_id=ctx.tenant_id,
kb_id=ctx.kb_id,
callback=_stage_cb("[wiki REDUCE]"),
)

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect whether REDUCE filters/cleans artifact_map_extract rows by current document eligibility.
ast-grep outline rag/advanced_rag/knowlege_compile/wiki.py --match wiki_reduce_from_extracts --view expanded
ast-grep run --pattern $'async def wiki_reduce_from_extracts($$$):\n    $$$' --lang python rag/advanced_rag/knowlege_compile/wiki.py
rg -nP 'artifact_map_extract|doc_id|compile_kwd|parser_config|compilation_template_group_id' -C3 rag/advanced_rag/knowlege_compile/wiki.py

Repository: infiniflow/ragflow

Length of output: 26874


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the orchestration around eligible docs and any cleanup of stale MAP rows.
sed -n '540,760p' rag/svr/task_executor_refactor/dataset_wiki_generator.py
printf '\n---\n'
rg -n "eligible|delete.*artifact_map_extract|wiki_reduce_from_extracts|force_rerun|input_hash|template_group" rag/svr/task_executor_refactor/dataset_wiki_generator.py rag/advanced_rag/knowlege_compile/wiki.py

Repository: infiniflow/ragflow

Length of output: 17284


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check whether eligibility changes already trigger any cleanup of wiki MAP rows.
rg -n "artifact_map_extract|wiki_map:|delete.*extract row|compilation_template_group_id|eligible.*artifacts|now has zero chunks" \
  rag api -g '!**/__pycache__/**'

Repository: infiniflow/ragflow

Length of output: 7297


Exclude ineligible docs from REDUCE input. wiki_reduce_from_extracts() still aggregates every artifact_map_extract row in the KB, so docs that drop out of the eligible set can keep contributing stale data unless those rows are removed elsewhere. Thread the eligible doc IDs through REDUCE or prune the old MAP rows when eligibility changes.

🤖 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 733 -
739, The REDUCE stage in wiki_reduce_from_extracts is still reading all
artifact_map_extract rows, so stale extracts from ineligible docs can continue
affecting output. Update the wiki generation flow around
dataset_wiki_generator.py and wiki_reduce_from_extracts to either pass the
current eligible document IDs into REDUCE and filter the input, or delete/prune
outdated MAP rows when eligibility changes. Make sure the fix is applied at the
call site where wiki_reduce_from_extracts is invoked and in the corresponding
data aggregation logic so only eligible docs contribute.

@codecov

codecov Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (404ef4c) to head (11bc06e).
⚠️ Report is 30 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16515   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng
yingfeng force-pushed the feat/knowledge_compilation_backend branch from e05f04b to 11bc06e Compare July 2, 2026 14:24
@yingfeng
yingfeng merged commit 62f94cd into infiniflow:main Jul 2, 2026
8 of 9 checks passed
@KevinHuSh
KevinHuSh deleted the feat/knowledge_compilation_backend branch July 3, 2026 05:50
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
## Summary
- Add knowledge compilation template APIs, services, and builtin
template seed data
- Add advanced knowledge compile structure/artifact/RAPTOR workflow
support
- Update parsing, dataset/document APIs, and supporting services for
compilation workflows
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
## Summary
- Add knowledge compilation template APIs, services, and builtin
template seed data
- Add advanced knowledge compile structure/artifact/RAPTOR workflow
support
- Update parsing, dataset/document APIs, and supporting services for
compilation workflows
This was referenced Jul 7, 2026
wangq8 added a commit that referenced this pull request Jul 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants